1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
declare(strict_types=1); |
4
|
|
|
|
5
|
|
|
namespace Patoui\Router; |
6
|
|
|
|
7
|
|
|
use InvalidArgumentException; |
8
|
|
|
use Prophecy\Exception\Doubler\MethodNotFoundException; |
9
|
|
|
|
10
|
|
|
class Route implements Routable |
11
|
|
|
{ |
12
|
|
|
/** @var string */ |
13
|
|
|
private $httpVerb; |
14
|
|
|
|
15
|
|
|
/** @var string */ |
16
|
|
|
private $path; |
17
|
|
|
|
18
|
|
|
/** @var string */ |
19
|
|
|
private $className; |
20
|
|
|
|
21
|
|
|
/** @var string */ |
22
|
|
|
private $classMethodName; |
23
|
|
|
|
24
|
|
|
/** @var array */ |
25
|
|
|
private $parameters; |
26
|
|
|
|
27
|
|
|
public function __construct( |
28
|
|
|
string $httpVerb, |
29
|
|
|
string $path, |
30
|
|
|
string $className, |
31
|
|
|
string $classMethodName |
32
|
|
|
) { |
33
|
|
|
if (! in_array($httpVerb, ['get', 'post'])) { |
34
|
|
|
throw new InvalidArgumentException( |
35
|
|
|
'Invalid http verb, must be: get or post' |
36
|
|
|
); |
37
|
|
|
} |
38
|
|
|
|
39
|
|
|
if (! class_exists($className) || ! method_exists($className, $classMethodName)) { |
40
|
|
|
throw new MethodNotFoundException( |
41
|
|
|
"Method '{$classMethodName}' not found on class '{$className}'", |
42
|
|
|
$className, |
43
|
|
|
$classMethodName |
44
|
|
|
); |
45
|
|
|
} |
46
|
|
|
|
47
|
|
|
$this->httpVerb = $httpVerb; |
48
|
|
|
$this->path = $path; |
49
|
|
|
$this->className = $className; |
50
|
|
|
$this->classMethodName = $classMethodName; |
51
|
|
|
$this->parameters = []; |
52
|
|
|
} |
53
|
|
|
|
54
|
|
|
public function getClassName() : string |
55
|
|
|
{ |
56
|
|
|
return $this->className; |
57
|
|
|
} |
58
|
|
|
|
59
|
|
|
public function getClassMethodName() : string |
60
|
|
|
{ |
61
|
|
|
return $this->classMethodName; |
62
|
|
|
} |
63
|
|
|
|
64
|
|
|
public function getHttpVerb() : string |
65
|
|
|
{ |
66
|
|
|
return $this->httpVerb; |
67
|
|
|
} |
68
|
|
|
|
69
|
|
|
public function isHttpVerbAndPathAMatch( |
70
|
|
|
string $httpVerb, |
71
|
|
|
string $path |
72
|
|
|
) : bool { |
73
|
|
|
$pathParts = explode('/', $path); |
74
|
|
|
$routePathParts = explode('/', $this->getPath()); |
75
|
|
|
|
76
|
|
|
foreach ($routePathParts as $key => $routePathPart) { |
77
|
|
|
if (isset($pathParts[$key]) && preg_match('/{.+}/', $routePathPart)) { |
78
|
|
|
$this->parameters[] = $pathParts[$key]; |
79
|
|
|
$routePathParts[$key] = $pathParts[$key]; |
80
|
|
|
} |
81
|
|
|
} |
82
|
|
|
|
83
|
|
|
$routePath = implode('/', $routePathParts); |
84
|
|
|
|
85
|
|
|
return strcasecmp($this->getHttpVerb(), $httpVerb) === 0 && |
86
|
|
|
trim($routePath, '/') === trim($path, '/'); |
87
|
|
|
} |
88
|
|
|
|
89
|
|
|
public function getPath() : string |
90
|
|
|
{ |
91
|
|
|
return $this->path; |
92
|
|
|
} |
93
|
|
|
|
94
|
|
|
public function getParameters() : array |
95
|
|
|
{ |
96
|
|
|
return $this->parameters; |
97
|
|
|
} |
98
|
|
|
} |
99
|
|
|
|