1
|
|
|
<?php |
2
|
|
|
namespace PHPico; |
3
|
|
|
|
4
|
|
|
class Router { |
5
|
|
|
|
6
|
|
|
/** |
7
|
|
|
* Get the base from any possible url |
8
|
|
|
* return string |
9
|
|
|
*/ |
10
|
|
|
public function base() |
|
|
|
|
11
|
|
|
{ |
12
|
|
|
$b = strtr($_SERVER['SCRIPT_NAME'], ['index.php'=>'']); |
13
|
|
|
return strtr($_SERVER['REQUEST_URI'], [$b => '/']); |
14
|
|
|
} |
15
|
|
|
|
16
|
|
|
/** |
17
|
|
|
* Executes an array of routes. Should be properly formatted: |
18
|
|
|
* ['regex'=>'class@method'] |
19
|
|
|
* ['regex'=> ['GET','class@method']] |
20
|
|
|
* By default index() method will be taken. |
21
|
|
|
* No need of /^...$/ inside of regex. |
22
|
|
|
* Returns false if route not found. |
23
|
|
|
* |
24
|
|
|
* @var $routes array The routes array |
25
|
|
|
* @return string|false |
26
|
|
|
*/ |
27
|
|
|
public function dispatch($routes) |
28
|
|
|
{ |
29
|
|
|
$result = null; |
|
|
|
|
30
|
|
|
foreach($routes as $regex => $callable){ |
31
|
|
|
$result = $this->execute($regex, $callable); |
32
|
|
|
if($result !== false) return $result; |
33
|
|
|
} |
34
|
|
|
return false; |
35
|
|
|
} |
36
|
|
|
|
37
|
|
|
/** |
38
|
|
|
* Executes the request this regex and the route params. Could be a callable. |
39
|
|
|
* @var $regex string The regex |
40
|
|
|
* @var $route string|callable The route to be executed |
41
|
|
|
* return string|boolean The result |
42
|
|
|
*/ |
43
|
|
|
public function execute($regex, $callable) |
|
|
|
|
44
|
|
|
{ |
45
|
|
|
if(is_array($callable)){ |
46
|
|
|
$callable = end($callable); |
47
|
|
|
foreach($callable as $conf){ |
48
|
|
|
if($conf !== $_SERVER['REQUEST_METHOD']) return false; |
49
|
|
|
} |
50
|
|
|
} |
51
|
|
|
|
52
|
|
|
if(preg_match('/^'.$regex.'$/', $this->base(), $matches)){ |
53
|
|
|
|
54
|
|
|
array_shift($matches); |
55
|
|
|
|
56
|
|
|
if(is_callable($callable)){ |
57
|
|
|
return call_user_func_array($callable, $matches); |
58
|
|
|
} |
59
|
|
|
|
60
|
|
|
list($class, $method) = explode('@', $callable); |
61
|
|
|
|
62
|
|
|
$method = !preg_match('/\@/', $callable) ? 'index' : $method ; |
63
|
|
|
$class = class_exists($class) ? $class : $callable; |
64
|
|
|
|
65
|
|
|
$c = new $class(); |
66
|
|
|
return call_user_func_array(array($c, $method), $matches); |
67
|
|
|
} |
68
|
|
|
return false; |
69
|
|
|
} |
70
|
|
|
} |
71
|
|
|
|
Instead of super-globals, we recommend to explicitly inject the dependencies of your class. This makes your code less dependent on global state and it becomes generally more testable: