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