Completed
Push — 4.0 ( b44693...cafdfc )
by Marco
02:39
created

Table::getRoutes()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 5
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 0
Metric Value
dl 0
loc 5
ccs 0
cts 2
cp 0
rs 9.4285
c 0
b 0
f 0
cc 1
eloc 2
nc 1
nop 0
crap 2
1
<?php namespace Comodojo\Dispatcher\Router;
2
3
use \Comodojo\Dispatcher\Components\AbstractModel;
4
use \Comodojo\Dispatcher\Cache\RouterCache;
5
use \Comodojo\Dispatcher\Router\Parser;
6
use \Comodojo\Dispatcher\Router\Route;
7
use \Comodojo\Dispatcher\Router\Model as Router;
8
use \Comodojo\Foundation\Base\Configuration;
9
use \Comodojo\SimpleCache\Manager as SimpleCacheManager;
10
use \Comodojo\Exception\DispatcherException;
11
use \Exception;
12
13
/**
14
 * @package     Comodojo Dispatcher
15
 * @author      Marco Giovinazzi <[email protected]>
16
 * @author      Marco Castiello <[email protected]>
17
 * @license     GPL-3.0+
18
 *
19
 * LICENSE:
20
 *
21
 * This program is free software: you can redistribute it and/or modify
22
 * it under the terms of the GNU Affero General Public License as
23
 * published by the Free Software Foundation, either version 3 of the
24
 * License, or (at your option) any later version.
25
 *
26
 * This program is distributed in the hope that it will be useful,
27
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
28
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
29
 * GNU Affero General Public License for more details.
30
 *
31
 * You should have received a copy of the GNU Affero General Public License
32
 * along with this program. If not, see <http://www.gnu.org/licenses/>.
33
 */
34
35
class Table extends AbstractModel {
36
37
    protected $routes = [];
38
    protected $router;
39
    protected $parser;
40
    protected $cache;
41
42
    public function __construct(
43
        SimpleCacheManager $cache,
44
        Router $router
45
    ) {
46
47
        parent::__construct($router->configuration, $router->logger);
0 ignored issues
show
Bug introduced by
The property configuration cannot be accessed from this context as it is declared protected in class Comodojo\Dispatcher\Traits\ConfigurationTrait.

This check looks for access to properties that are not accessible from the current context.

If you need to make a property accessible to another context you can either raise its visibility level or provide an accessible getter in the defining class.

Loading history...
Bug introduced by
The property logger cannot be accessed from this context as it is declared protected in class Comodojo\Dispatcher\Traits\LoggerTrait.

This check looks for access to properties that are not accessible from the current context.

If you need to make a property accessible to another context you can either raise its visibility level or provide an accessible getter in the defining class.

Loading history...
48
49
        $this->router = $router;
50
        $this->parser = new Parser($this->logger);
51
        $this->cache = new RouterCache($cache);
52
53
        $this->readCache();
54
55
    }
56
57 1
    public function add($route, $type, $class, $parameters = array()) {
58
59 1
        $routeData = $this->get($route);
60
61 1
        if (!is_null($routeData)) {
62
63
            $routeData->setType($type)
64
                ->setClassName($class)
65
                ->setParameters($parameters);
66
67
        } else {
68
69 1
            $folders = explode("/", $route);
70
71 1
            $this->register($folders, $type, $class, $parameters);
72
73
        }
74
75 1
        return $this;
76
77
    }
78
79
    public function count() {
80
81
        return count($this->routes);
82
83
    }
84
85
    public function getRoutes() {
86
87
        return $this->routes;
88
89
    }
90
91 1
    public function get($route) {
92
93 1
        $regex = $this->regex($route);
94
95 1
        if (isset($this->routes[$regex])) {
96 1
            return $this->routes[$regex];
97
        }
98
99 1
        return null;
100
101
    }
102
103 1
    public function regex($route) {
104
105 1
        $folders = explode("/", $route);
106
107 1
        return $this->parser->read($folders);
108
109
    }
110
111 1
    public function remove($route) {
112
113 1
        $regex = $this->regex($route);
114
115 1
        $routes = $this->routes;
116
117 1
        if (isset($routes[$regex])) {
118
119 1
            unset($routes[$regex]);
120
121 1
            $this->routes = $routes;
122
123 1
            return true;
124
125
        }
126
127
        return false;
128
129
    }
130
131
    public function defaultRoute() {
132
133
        return $this->get('/');
134
135
    }
136
137
    public function load($routes) {
138
139
        if ( !empty($routes) ) {
140
141
            foreach( $routes as $name => $route ) {
142
143
                $this->add($route['route'], $route['type'], $route['class'], $route['parameters']);
144
                // $this->add($name, $route['type'], $route['class'], $route['parameters']);
0 ignored issues
show
Unused Code Comprehensibility introduced by
81% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
145
146
            }
147
148
        }
149
150
        $count = $this->count();
151
        $this->logger->debug("$count routes loaded in routing table");
152
153
        $this->dumpCache();
154
155
    }
156
157
    private function readCache() {
158
159
        if ( $this->configuration->get('routing-table-cache') !== true ) return;
160
161
        $data = $this->cache->read();
162
163
        if ( is_null($data) ) {
164
165
            $this->routes = [];
166
167
            return;
168
169
        }
170
171
        $this->routes = $data;
172
173
        $this->logger->debug("Routing table loaded from cache");
174
175
    }
176
177
    private function dumpCache() {
178
179
        if ( $this->configuration->get('routing-table-cache') !== true ) return;
180
181
        $ttl = $this->configuration->get('routing-table-ttl');
182
183
        if ( $this->cache->dump($this->routes, $ttl) ) {
184
            $this->logger->debug("Routing table saved to cache");
185
        } else {
186
            $this->logger->warning("Cannot save routing table to cache");
187
        }
188
189
    }
190
191
    // This method add a route to the supported list
192 1
    private function register($folders, $type, $class, $parameters) {
193
194
        // The values associated with a route are as follows:
195
        // $route = new Route($this->router);
0 ignored issues
show
Unused Code Comprehensibility introduced by
50% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
196 1
        $route = new Route();
197 1
        $route->setType($type) // Type of route
198 1
            ->setClassName($class) // Class to be invoked
199 1
            ->setParameters($parameters); // Parameters passed via the composer.json configuration (cache, ttl, etc...)
200
201 1
        $this->logger->debug("Route table - route: " . implode("/", $folders));
202
203
        // This method generate a global regular expression which will be able to match all the URI supported by the route
204 1
        $regex = $this->parser->read($folders, $route);
205
206 1
        $this->logger->debug("Route table - route regex: $regex");
207
208 1
        $this->routes = array_merge($this->routes, [$regex => $route]);
209
210 1
    }
211
212
}
213