1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace Core\ControllerDispatcher; |
4
|
|
|
|
5
|
|
|
use Prob\Router\Map; |
6
|
|
|
use Core\ControllerDispatcher; |
7
|
|
|
|
8
|
|
|
class RouterMapBuilder |
9
|
|
|
{ |
10
|
|
|
private $routerConfig = []; |
11
|
|
|
|
12
|
|
|
public function __construct(array $config = []) |
13
|
|
|
{ |
14
|
|
|
$this->setRouterConfig($config); |
15
|
|
|
} |
16
|
|
|
|
17
|
|
|
public function setRouterConfig(array $config) |
18
|
|
|
{ |
19
|
|
|
$this->routerConfig = $config; |
20
|
|
|
} |
21
|
|
|
|
22
|
|
|
public function build() |
23
|
|
|
{ |
24
|
|
|
$map = new Map(); |
25
|
|
|
$map->setNamespace($this->routerConfig['namespace']); |
26
|
|
|
|
27
|
|
|
foreach ($this->getRoutePaths() as $k => $v) { |
28
|
|
|
$this->addRouterPath($map, $k, $v); |
29
|
|
|
} |
30
|
|
|
|
31
|
|
|
return $map; |
32
|
|
|
} |
33
|
|
|
|
34
|
|
|
private function getRoutePaths() |
35
|
|
|
{ |
36
|
|
|
$paths = $this->routerConfig; |
37
|
|
|
unset($paths['namespace']); |
38
|
|
|
|
39
|
|
|
return $paths; |
40
|
|
|
} |
41
|
|
|
|
42
|
|
|
/** |
43
|
|
|
* $handlers schema |
44
|
|
|
* (string) $handlers method or function name | {closure} |
45
|
|
|
* (array) $handlers['GET' | 'POST'] => method or function name | {closure} |
46
|
|
|
* |
47
|
|
|
* @param Map $routerMap |
48
|
|
|
* @param string $path url path |
49
|
|
|
* @param string|array|closure $handlers |
50
|
|
|
*/ |
51
|
|
|
private function addRouterPath(Map $routerMap, $path, $handlers) |
52
|
|
|
{ |
53
|
|
|
if ($this->getHttpHandler('GET', $handlers)) { |
54
|
|
|
$routerMap->get($path, $this->getHttpHandler('GET', $handlers)); |
55
|
|
|
} |
56
|
|
|
|
57
|
|
|
if ($this->getHttpHandler('POST', $handlers)) { |
58
|
|
|
$routerMap->post($path, $this->getHttpHandler('POST', $handlers)); |
59
|
|
|
} |
60
|
|
|
} |
61
|
|
|
|
62
|
|
|
private function getHttpHandler($method, $handlers) |
63
|
|
|
{ |
64
|
|
|
if (gettype($handlers) === 'string' || is_callable($handlers)) { |
65
|
|
|
return $method === 'GET' ? $handlers : null; |
66
|
|
|
} |
67
|
|
|
|
68
|
|
|
return isset($handlers[$method]) ? $handlers[$method] : null; |
69
|
|
|
} |
70
|
|
|
} |
71
|
|
|
|