Completed
Push — master ( 23f42c...e6b3d9 )
by Park Jong-Hun
02:39
created

RouterMapBuilder   A

Complexity

Total Complexity 13

Size/Duplication

Total Lines 64
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 1

Importance

Changes 1
Bugs 0 Features 0
Metric Value
wmc 13
c 1
b 0
f 0
lcom 1
cbo 1
dl 0
loc 64
rs 10

6 Methods

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