Completed
Push — master ( 857f68...f292c4 )
by Pierre
02:57
created

Routes   A

Complexity

Total Complexity 10

Size/Duplication

Total Lines 91
Duplicated Lines 0 %

Test Coverage

Coverage 100%

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 24
c 1
b 0
f 0
dl 0
loc 91
ccs 29
cts 29
cp 1
rs 10
wmc 10

6 Methods

Rating   Name   Duplication   Size   Complexity  
A validate() 0 7 3
A getExpr() 0 9 1
A set() 0 6 1
A get() 0 3 1
A prepare() 0 7 2
A __construct() 0 6 2
1
<?php
2
3
namespace App\Component\Http;
4
5
use App\Component\Http\Interfaces\IRoutes;
6
use App\Component\Http\Route;
7
8
class Routes implements IRoutes
9
{
10
11
    /**
12
     * route list as array
13
     *
14
     * @var array
15
     */
16
    private $routes = [];
17
18
    /**
19
     * __construct
20
     *
21
     * @param array $routesConfig
22
     * @return Routes
23
     */
24 5
    public function __construct(array $routesConfig = [])
25
    {
26 5
        if (!empty($routesConfig)) {
27 5
            $this->set($routesConfig);
28
        }
29 5
        return $this;
30
    }
31
32
    /**
33
     * set routes as array and stack Route collection
34
     *
35
     * @param array $routesConfig
36
     * @return Routes
37
     */
38 5
    public function set(array $routesConfig): Routes
39
    {
40 5
        $this->routes = [];
41 5
        $this->prepare($routesConfig);
42 5
        $this->validate();
43 5
        return $this;
44
    }
45
46
    /**
47
     * returns routes as array
48
     *
49
     * @return array
50
     */
51 1
    public function get(): array
52
    {
53 1
        return $this->routes;
54
    }
55
56
    /**
57
     * returns routes as array
58
     *
59
     * @return array
60
     */
61 2
    public function getExpr(): array
62
    {
63 2
        $patterns = array_map(
64 2
            function (Route $i) {
65 2
                return $i->getExpr();
66 2
            },
67 2
            $this->routes
68
        );
69 2
        return $patterns;
70
    }
71
72
    /**
73
     * stacks routes as Route object collection from routes config
74
     *
75
     * @param array $routesConfig
76
     * @return Routes
77
     */
78 1
    protected function prepare(array $routesConfig): Routes
79
    {
80 1
        $count = count($routesConfig);
81 1
        for ($c = 0; $c < $count; $c++) {
82 1
            $this->routes[] = new Route($routesConfig[$c]);
83
        }
84 1
        return $this;
85
    }
86
87
    /**
88
     * validate routes to be an array of regexp string
89
     *
90
     * @throws Exception
91
     */
92 2
    protected function validate()
93
    {
94 2
        $count = count($this->routes);
95 2
        for ($c = 0; $c < $count; $c++) {
96 2
            $route = $this->routes[$c]->getExpr();
97 2
            if (@preg_match($route, null) === false) {
98 1
                throw new \Exception('Route invalid expr ' . $route);
99
            }
100
        }
101
    }
102
}
103