1
|
|
|
<?php |
2
|
|
|
/** |
3
|
|
|
* Pimf |
4
|
|
|
* |
5
|
|
|
* @copyright Copyright (c) Gjero Krsteski (http://krsteski.de) |
6
|
|
|
* @license http://opensource.org/licenses/MIT MIT |
7
|
|
|
*/ |
8
|
|
|
|
9
|
|
|
namespace Pimf; |
10
|
|
|
|
11
|
|
|
use Pimf\Route\Target; |
12
|
|
|
|
13
|
|
|
/** |
14
|
|
|
* Router |
15
|
|
|
* |
16
|
|
|
* This class is responsible for registering route objects, assigning names to route objects, |
17
|
|
|
* finding routes that match the current HTTP request, and creating URLs for a named route. |
18
|
|
|
* |
19
|
|
|
* @package Pimf |
20
|
|
|
* @author Gjero Krsteski <[email protected]> |
21
|
|
|
*/ |
22
|
|
|
class Router |
23
|
|
|
{ |
24
|
|
|
/** |
25
|
|
|
* @var Route[] |
26
|
|
|
*/ |
27
|
|
|
protected $routes = array(); |
28
|
|
|
|
29
|
|
|
public function __construct() |
30
|
|
|
{ |
31
|
|
|
//it is a pimf-framework restriction. |
32
|
|
|
$this->map(new Route('/:controller')) |
33
|
|
|
->map(new Route('/:controller/:action')) |
34
|
|
|
->map(new Route('/:controller/:action/:id')); |
35
|
|
|
} |
36
|
|
|
|
37
|
|
|
/** |
38
|
|
|
* @param Route $route |
39
|
|
|
* |
40
|
|
|
* @return Router |
41
|
|
|
*/ |
42
|
|
|
public function map(Route $route) |
43
|
|
|
{ |
44
|
|
|
$this->routes[$route->init()->getRule()] = $route; |
45
|
|
|
|
46
|
|
|
return $this; |
47
|
|
|
} |
48
|
|
|
|
49
|
|
|
/** |
50
|
|
|
* @param Route $route |
51
|
|
|
* |
52
|
|
|
* @return Target |
53
|
|
|
*/ |
54
|
|
|
private function target(Route $route) |
55
|
|
|
{ |
56
|
|
|
$params = $route->getParams(); |
57
|
|
|
|
58
|
|
|
$target = new Target($params['controller']); |
59
|
|
|
|
60
|
|
|
unset($params['controller']); |
61
|
|
|
|
62
|
|
|
if (isset($params['action'])) { |
63
|
|
|
$target->setAction($params['action']); |
64
|
|
|
unset($params['action']); |
65
|
|
|
} |
66
|
|
|
|
67
|
|
|
$target->setParams($params); |
68
|
|
|
|
69
|
|
|
return $target; |
70
|
|
|
} |
71
|
|
|
|
72
|
|
|
/** |
73
|
|
|
* @return bool|Target |
74
|
|
|
*/ |
75
|
|
|
public function find() |
76
|
|
|
{ |
77
|
|
|
// check custom routes first |
78
|
|
|
// than framework's restriction routes. |
79
|
|
|
foreach (array_reverse($this->routes) as $route) { |
80
|
|
|
if ($route->matches() === true) { |
81
|
|
|
return $this->target($route); |
82
|
|
|
} |
83
|
|
|
} |
84
|
|
|
|
85
|
|
|
return false; |
86
|
|
|
} |
87
|
|
|
} |
88
|
|
|
|