-
Notifications
You must be signed in to change notification settings - Fork 0
/
Route.php
118 lines (101 loc) · 2.63 KB
/
Route.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
<?php
declare(strict_types=1);
/**
* Class Route
* @package DevCoder
*/
final class Route
{
/**
* @var string
*/
private $name;
/**
* @var string
*/
private $path;
/**
* @var array<string>
*/
private $parameters = [];
/**
* @var array<string>
*/
private $methods = [];
/**
* @var array<string>
*/
private $vars = [];
/**
* Route constructor.
* @param string $name
* @param string $path
* @param array $parameters
* $parameters = [
* 0 => (string) Controller name : HomeController::class.
* 1 => (string|null) Method name or null if invoke method
* ]
* @param array $methods
*/
public function __construct(string $name, string $path, array $parameters, array $methods = ['GET'])
{
if ($methods === []) {
throw new \InvalidArgumentException('HTTP methods argument was empty; must contain at least one method');
}
$this->name = $name;
$this->path = $path;
$this->parameters = $parameters;
$this->methods = $methods;
}
public function match(string $path, string $method): bool
{
$regex = $this->getPath();
foreach ($this->getVarsNames() as $variable) {
$varName = trim($variable, '{\}');
$regex = str_replace($variable, '(?P<' . $varName . '>[^/]++)', $regex);
}
if (in_array($method, $this->getMethods()) && preg_match('#^' . $regex . '$#sD', self::trimPath($path), $matches)) {
$values = array_filter($matches, static function ($key) {
return is_string($key);
}, ARRAY_FILTER_USE_KEY);
foreach ($values as $key => $value) {
$this->vars[$key] = $value;
}
return true;
}
return false;
}
public function getName(): string
{
return $this->name;
}
public function getPath(): string
{
return $this->path;
}
public function getParameters(): array
{
return $this->parameters;
}
public function getMethods(): array
{
return $this->methods;
}
public function getVarsNames(): array
{
preg_match_all('/{[^}]*}/', $this->path, $matches);
return reset($matches) ?? [];
}
public function hasVars(): bool
{
return $this->getVarsNames() !== [];
}
public function getVars(): array
{
return $this->vars;
}
public static function trimPath(string $path): string
{
return '/' . rtrim(ltrim(trim($path), '/'), '/');
}
}