Completed
Push — 4.0 ( 75a76e...0161d2 )
by Marco
14:59
created

Collector::dumpCache()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 9
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 1 Features 0
Metric Value
c 1
b 1
f 0
dl 0
loc 9
rs 9.6666
cc 1
eloc 4
nc 1
nop 0
1
<?php namespace Comodojo\Dispatcher\Router;
2
3
use \Comodojo\Dispatcher\Components\Model as DispatcherClassModel;
4
use \Comodojo\Dispatcher\Router\RoutingTable;
5
use \Comodojo\Dispatcher\Components\Timestamp as TimestampTrait;
6
use \Comodojo\Dispatcher\Request\Model as Request;
7
use \Comodojo\Dispatcher\Response\Model as Response;
8
use \Comodojo\Dispatcher\Extra\Model as Extra;
9
use \Comodojo\Dispatcher\Components\Configuration;
10
use \Comodojo\Cache\CacheManager;
11
use \Symfony\Component\Yaml\Yaml;
12
use \Monolog\Logger;
13
use \Comodojo\Exception\DispatcherException;
14
use \Exception;
15
16
/**
17
 * @package     Comodojo Dispatcher
18
 * @author      Marco Giovinazzi <[email protected]>
19
 * @author      Marco Castiello <[email protected]>
20
 * @license     GPL-3.0+
21
 *
22
 * LICENSE:
23
 *
24
 * This program is free software: you can redistribute it and/or modify
25
 * it under the terms of the GNU Affero General Public License as
26
 * published by the Free Software Foundation, either version 3 of the
27
 * License, or (at your option) any later version.
28
 *
29
 * This program is distributed in the hope that it will be useful,
30
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
31
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
32
 * GNU Affero General Public License for more details.
33
 *
34
 * You should have received a copy of the GNU Affero General Public License
35
 * along with this program. If not, see <http://www.gnu.org/licenses/>.
36
 */
37
38
class Collector extends DispatcherClassModel {
39
40
    use TimestampTrait;
41
42
    private $bypass = false;
43
44
    private $classname = "";
45
46
    private $type = "";
47
48
    private $service = "";
49
50
    private $cache;
51
52
    private $request;
53
54
    private $response;
55
56
    private $table;
57
58
    public function __construct(
59
        Configuration $configuration,
60
        Logger $logger,
61
        CacheManager $cache,
62
        Extra $extra = null
63
    ) {
64
65
        parent::__construct($configuration, $logger);
66
67
        $this->table = new RoutingTable($logger);
68
69
        $this->cache = $cache;
70
71
        $this->extra = $extra;
0 ignored issues
show
Bug introduced by
The property extra does not exist. Did you maybe forget to declare it?

In PHP it is possible to write to properties without declaring them. For example, the following is perfectly valid PHP code:

class MyClass { }

$x = new MyClass();
$x->foo = true;

Generally, it is a good practice to explictly declare properties to avoid accidental typos and provide IDE auto-completion:

class MyClass {
    public $foo;
}

$x = new MyClass();
$x->foo = true;
Loading history...
72
73
        $this->setTimestamp();
74
75
    }
76
77
    public function getType() {
78
79
        return $this->type;
80
81
    }
82
83
    public function getService() {
84
85
        return $this->service;
86
87
    }
88
89
    public function getParameters() {
90
91
        return $this->parameters;
0 ignored issues
show
Bug introduced by
The property parameters does not exist. Did you maybe forget to declare it?

In PHP it is possible to write to properties without declaring them. For example, the following is perfectly valid PHP code:

class MyClass { }

$x = new MyClass();
$x->foo = true;

Generally, it is a good practice to explictly declare properties to avoid accidental typos and provide IDE auto-completion:

class MyClass {
    public $foo;
}

$x = new MyClass();
$x->foo = true;
Loading history...
92
93
    }
94
95
    public function getClassName() {
96
97
        return $this->classname;
98
99
    }
100
101
    public function getInstance() {
102
103
        $class = $this->classname;
104
105
        if (class_exists($class)) {
106
107
            return new $class(
108
                $this->configuration,
109
                $this->logger,
110
                $this->request,
111
                $this,
112
                $this->response,
113
                $this->extra
114
            );
115
116
        }
117
        else return null;
118
119
    }
120
121
    public function add($route, $type, $class, $parameters = array()) {
122
123
        $routeData = $this->get($route);
124
125
        if (is_null($routeData)) {
126
127
            $this->table->put($route, $type, $class, $parameters);
128
129
        } else {
130
131
            $this->table->set($route, $type, $class, $parameters);
132
133
        }
134
135
    }
136
137
    public function get($route) {
138
139
        return $this->table->get($route);
140
141
    }
142
143
    public function remove($route) {
144
145
        return $this->table->remove($route);
146
147
    }
148
149
    public function bypass($mode = true) {
150
151
        $this->bypass = filter_var($mode, FILTER_VALIDATE_BOOLEAN);
152
153
        return $this;
154
155
    }
156
157
    public function route(Request $request) {
158
159
        $method = $request->method()->get();
160
161
        $methods = $this->configuration->get('allowed-http-methods');
162
163
        if ( ( $methods != null || !empty($methods) ) && in_array($method, $methods) === false ) {
164
165
            throw new DispatcherException("Method not allowed", 0, null, 405, array(
0 ignored issues
show
Unused Code introduced by
The call to DispatcherException::__construct() has too many arguments starting with array('Allow' => implode(',', $methods)).

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
166
                "Allow" => implode(",",$methods)
167
            ));
168
169
        }
170
171
        $this->request = $request;
172
173
        if (!$this->parse()) {
174
175
            throw new DispatcherException("Unable to find a valid route for the specified uri", 0, null, 404);
176
177
        }
178
179
    }
180
181
    public function compose(Response $response) {
182
183
        $this->response = $response;
184
185
        $service = $this->getInstance();
186
187
        if (!is_null($service)) {
188
189
            $result;
0 ignored issues
show
Bug introduced by
The variable $result seems only to be defined at a later point. Did you maybe move this code here without moving the variable definition?

This error can happen if you refactor code and forget to move the variable initialization.

Let’s take a look at a simple example:

function someFunction() {
    $x = 5;
    echo $x;
}

The above code is perfectly fine. Now imagine that we re-order the statements:

function someFunction() {
    echo $x;
    $x = 5;
}

In that case, $x would be read before it is initialized. This was a very basic example, however the principle is the same for the found issue.

Loading history...
190
191
            $method = $this->request->method()->get();
192
193
            $methods = $service->getImplementedMethods();
194
195
            if ( in_array($method, $methods) ) {
196
197
                $callable = $service->getMethod($method);
198
199
                try {
200
201
                    $result = call_user_func(array($service, $callable));
202
203
                } catch (DispatcherException $de) {
204
205
                    throw new DispatcherException(sprintf("Service '%s' exception for method '%s': %s", $this->service, $method, $de->getMessage()), 0, $de, 500);
206
207
                } catch (Exception $e) {
208
209
                    throw new DispatcherException(sprintf("Service '%s' execution failed for method '%s': %s", $this->service, $method, $e->getMessage()), 0, $e, 500);
210
211
                }
212
213
            } else {
214
215
                throw new DispatcherException(sprintf("Service '%s' doesn't implement method '%s'", $this->service, $method), 0, null, 501, array(
0 ignored issues
show
Unused Code introduced by
The call to DispatcherException::__construct() has too many arguments starting with array('Allow' => implode(',', $methods)).

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
216
                    "Allow" => implode(",", $methods)
217
                ));
218
219
            }
220
221
            $this->response->content()->set($result);
222
223
        } else {
224
225
            throw new DispatcherException(sprintf("Unable to execute service '%s'", $this->service), 0, null, 500);
226
227
        }
228
229
    }
230
231
    public function loadFromYaml($yaml) {
232
233
        $routes = Yaml::parse($yaml);
234
235
        if ( !empty($routes) ) {
236
237
            foreach( $routes as $name => $route ) {
0 ignored issues
show
Bug introduced by
The expression $routes of type array|string|object<stdClass> is not guaranteed to be traversable. How about adding an additional type check?

There are different options of fixing this problem.

  1. If you want to be on the safe side, you can add an additional type-check:

    $collection = json_decode($data, true);
    if ( ! is_array($collection)) {
        throw new \RuntimeException('$collection must be an array.');
    }
    
    foreach ($collection as $item) { /** ... */ }
    
  2. If you are sure that the expression is traversable, you might want to add a doc comment cast to improve IDE auto-completion and static analysis:

    /** @var array $collection */
    $collection = json_decode($data, true);
    
    foreach ($collection as $item) { /** .. */ }
    
  3. Mark the issue as a false-positive: Just hover the remove button, in the top-right corner of this issue for more options.

Loading history...
238
239
                $this->add($route['route'], $route['type'], $route['class'], $route['parameters']);
240
241
            }
242
243
        }
244
245
        return $this->dumpCache();
246
247
    }
248
    
249
    public function loadFromCache() {
250
        
251
        $routes = $this->cache->get("dispatcher_routes");
252
        
253
        if (is_null($routes)) return null;
254
        
255
        $this->table->routes($routes);
256
        
257
        return $this;
258
        
259
    }
260
    
261
    private function dumpCache() {
262
        
263
        $routes = $this->table->routes();
264
        
265
        $this->cache->set("dispatcher_routes", $routes, 24 * 60 * 60);
266
        
267
        return $this;
268
        
269
    }
270
271
    private function parse() {
272
273
        $path = $this->request->route();
274
        
275
        foreach ($this->table->routes() as $regex => $value) {
0 ignored issues
show
Bug introduced by
The expression $this->table->routes() of type array|object<Comodojo\Di...er\Router\RoutingTable> is not guaranteed to be traversable. How about adding an additional type check?

There are different options of fixing this problem.

  1. If you want to be on the safe side, you can add an additional type-check:

    $collection = json_decode($data, true);
    if ( ! is_array($collection)) {
        throw new \RuntimeException('$collection must be an array.');
    }
    
    foreach ($collection as $item) { /** ... */ }
    
  2. If you are sure that the expression is traversable, you might want to add a doc comment cast to improve IDE auto-completion and static analysis:

    /** @var array $collection */
    $collection = json_decode($data, true);
    
    foreach ($collection as $item) { /** .. */ }
    
  3. Mark the issue as a false-positive: Just hover the remove button, in the top-right corner of this issue for more options.

Loading history...
276
            
277
            // The current uri is checked against all the global regular expressions associated with the routes
278
            if (preg_match("/" . $regex . "/", $path, $matches)) {
279
280
                /* If a route is matched, all the bits of the route string are evalued in order to create
281
                 * new query parameters which will be available for the service class
282
                 */
283
                $this->evalUri($value['query'], $matches);
284
285
                // All the route parameters are also added to the query parameters
286
                foreach ($value['parameters'] as $parameter => $value) {
287
288
                    $this->request->query()->set($parameter, $value);
289
290
                }
291
292
                $this->classname  = $value['class'];
293
                $this->type       = $value['type'];
294
                $this->service    = implode('.', $value['service']);
295
                $this->service    = empty($this->service)?"default":$this->service;
296
297
                return true;
298
299
            }
300
301
        }
302
303
        return false;
304
305
    }
306
307
    private function evalUri($parameters, $bits) {
308
309
        $count  = 0;
0 ignored issues
show
Unused Code introduced by
$count is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
310
311
        // Because of the nature of the global regular expression, all the bits of the matched route are associated with a parameter key
312
        foreach ($parameters as $key => $value) {
313
314
            if (isset($bits[$key])) {
315
                /* if it's available a bit associated with the parameter name, it is compared against
316
                 * it's regular expression in order to extrect backreferences
317
                 */
318
                if (preg_match('/^' . $value['regex'] . '$/', $bits[$key], $matches)) {
319
                    
320
                    if (count($matches) == 1) $matches = $matches[0]; // This is the case where no backreferences are present or available.
321
                    
322
                    // The extracted value (with any backreference available) is added to the query parameters.
323
                    $this->request->query()->set($key, $matches);
324
325
                }
326
327
            } elseif ($value['required']) {
328
329
                throw new DispatcherException(sprintf("Required parameter '%s' not specified.", $key), 1, null, 500);
330
331
            }
332
333
        }
334
335
    }
336
337
}
338