|
1
|
|
|
<?php |
|
2
|
|
|
declare(strict_types = 1); |
|
3
|
|
|
|
|
4
|
|
|
namespace Zortje\MVC\Routing; |
|
5
|
|
|
|
|
6
|
|
|
use Zortje\MVC\Routing\Exception\RouteAlreadyConnectedException; |
|
7
|
|
|
use Zortje\MVC\Routing\Exception\RouteNonexistentException; |
|
8
|
|
|
|
|
9
|
|
|
/** |
|
10
|
|
|
* Class Router |
|
11
|
|
|
* |
|
12
|
|
|
* @package Zortje\MVC\Routing |
|
13
|
|
|
*/ |
|
14
|
|
|
class Router |
|
15
|
|
|
{ |
|
16
|
|
|
|
|
17
|
|
|
/** |
|
18
|
|
|
* @var array Routes |
|
19
|
|
|
*/ |
|
20
|
|
|
protected $routes = []; |
|
21
|
|
|
|
|
22
|
|
|
/** |
|
23
|
|
|
* Connects a new route in the router |
|
24
|
|
|
* |
|
25
|
|
|
* @param string $route Route |
|
26
|
|
|
* @param string $controller Controller |
|
27
|
|
|
* @param string $action Action |
|
28
|
|
|
* |
|
29
|
|
|
* @throws RouteAlreadyConnectedException When route is already connected |
|
30
|
|
|
*/ |
|
31
|
3 |
|
public function connect(string $route, string $controller, string $action) |
|
32
|
|
|
{ |
|
33
|
3 |
|
if (isset($this->routes[$route]) === true) { |
|
34
|
1 |
|
throw new RouteAlreadyConnectedException([$route]); |
|
35
|
|
|
} |
|
36
|
|
|
|
|
37
|
3 |
|
$this->routes[$route] = [ |
|
38
|
3 |
|
'controller' => $controller, |
|
39
|
3 |
|
'action' => $action |
|
40
|
|
|
]; |
|
41
|
3 |
|
} |
|
42
|
|
|
|
|
43
|
|
|
/** |
|
44
|
|
|
* Route to get controller and action |
|
45
|
|
|
* |
|
46
|
|
|
* @param string $route Route |
|
47
|
|
|
* |
|
48
|
|
|
* @return array Controller and action |
|
49
|
|
|
* |
|
50
|
|
|
* @throws RouteNonexistentException When route is not connected |
|
51
|
|
|
*/ |
|
52
|
3 |
|
public function route(string $route): array |
|
53
|
|
|
{ |
|
54
|
3 |
|
foreach ($this->routes as $pattern => $result) { |
|
55
|
2 |
|
if (preg_match("/$pattern/", $route, $matches)) { |
|
56
|
2 |
|
array_shift($matches); |
|
57
|
|
|
|
|
58
|
2 |
|
$result['arguments'] = $matches; |
|
59
|
|
|
|
|
60
|
2 |
|
return $result; |
|
61
|
|
|
} |
|
62
|
|
|
} |
|
63
|
|
|
|
|
64
|
|
|
/** |
|
65
|
|
|
* Throw exception if no match for route is found |
|
66
|
|
|
*/ |
|
67
|
1 |
|
throw new RouteNonexistentException([$route]); |
|
68
|
|
|
} |
|
69
|
|
|
} |
|
70
|
|
|
|