1
|
|
|
<?php |
2
|
|
|
namespace Nkey\Caribu\Mvc\Router; |
3
|
|
|
|
4
|
|
|
use Nkey\Caribu\Mvc\Controller\AbstractController; |
5
|
|
|
use Nkey\Caribu\Mvc\Controller\Request; |
6
|
|
|
use Nkey\Caribu\Mvc\Application; |
7
|
|
|
|
8
|
|
|
abstract class AbstractRouter { |
9
|
|
|
|
10
|
|
|
/** |
11
|
|
|
* Application instance |
12
|
|
|
* |
13
|
|
|
* @var Application |
14
|
|
|
*/ |
15
|
|
|
private $application; |
16
|
|
|
|
17
|
2 |
|
public function setApplication(Application $application) |
18
|
|
|
{ |
19
|
2 |
|
$this->application = $application; |
20
|
2 |
|
foreach($this->routes as $routeName => $controller) { |
21
|
2 |
|
$this->application->registerController($controller, $routeName); |
22
|
|
|
} |
23
|
2 |
|
} |
24
|
|
|
|
25
|
|
|
/** |
26
|
|
|
* @var array |
27
|
|
|
*/ |
28
|
|
|
private $routes; |
29
|
|
|
|
30
|
2 |
|
public function addRoute(string $name, AbstractController $controller) |
31
|
|
|
{ |
32
|
2 |
|
$this->routes[$name] = $controller; |
33
|
2 |
|
} |
34
|
|
|
|
35
|
|
|
/** |
36
|
|
|
* Checks wether a route exists |
37
|
|
|
* |
38
|
|
|
* @param string $name |
39
|
|
|
* @return bool |
40
|
|
|
*/ |
41
|
2 |
|
public function hasRoute(string $name) |
42
|
|
|
{ |
43
|
2 |
|
return key_exists($name, $this->routes); |
44
|
|
|
} |
45
|
|
|
|
46
|
|
|
/** |
47
|
|
|
* |
48
|
|
|
* @param string $name |
49
|
|
|
* @throws RouterException |
50
|
|
|
* @return AbstractController |
51
|
|
|
*/ |
52
|
1 |
|
private function getRoute(string $name) |
53
|
|
|
{ |
54
|
1 |
|
if(!$this->hasRoute($name)) { |
55
|
|
|
throw new RouterException("Router {$router} is not registered"); |
56
|
|
|
} |
57
|
|
|
|
58
|
1 |
|
return $this->routes[$name]; |
59
|
|
|
} |
60
|
|
|
|
61
|
|
|
/** |
62
|
|
|
* Route the existing request into a new controller |
63
|
|
|
* |
64
|
|
|
* @param string $name The name of route |
65
|
|
|
* @param Request $request The existing request instance |
66
|
|
|
* @return \Nkey\Caribu\Mvc\Controller\AbstractController |
67
|
|
|
*/ |
68
|
1 |
|
public function route(string $name, Request $request) |
69
|
|
|
{ |
70
|
1 |
|
$parts = \explode('/', $request->getOrigin()); |
71
|
1 |
|
$found = false; |
72
|
1 |
|
for($i = 0; $i < count($parts); $i++) { |
|
|
|
|
73
|
1 |
|
if($parts[$i] === $name && isset($parts[$i+1])) { |
74
|
|
|
$request->setAction($parts[$i+1]); |
75
|
|
|
$found = true; |
76
|
|
|
} |
77
|
|
|
} |
78
|
1 |
|
if(!$found) { |
79
|
1 |
|
$request->setAction("index"); |
80
|
|
|
} |
81
|
1 |
|
return $this->getRoute($name); |
82
|
|
|
} |
83
|
|
|
} |
If the size of the collection does not change during the iteration, it is generally a good practice to compute it beforehand, and not on each iteration: