Completed
Push — 4.0 ( 25fc97...6a2270 )
by Marco
16:06
created

Model::parse()   B

Complexity

Conditions 5
Paths 4

Size

Total Lines 38
Code Lines 14

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 38
rs 8.439
cc 5
eloc 14
nc 4
nop 0
1
<?php namespace Comodojo\Dispatcher\Router;
2
3
use \Comodojo\Dispatcher\Components\Model as DispatcherClassModel;
4
use \Comodojo\Dispatcher\Router\Table;
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 \Monolog\Logger;
12
use \Comodojo\Exception\DispatcherException;
13
use \Exception;
14
15
/**
16
 * @package     Comodojo Dispatcher
17
 * @author      Marco Giovinazzi <[email protected]>
18
 * @author      Marco Castiello <[email protected]>
19
 * @license     GPL-3.0+
20
 *
21
 * LICENSE:
22
 *
23
 * This program is free software: you can redistribute it and/or modify
24
 * it under the terms of the GNU Affero General Public License as
25
 * published by the Free Software Foundation, either version 3 of the
26
 * License, or (at your option) any later version.
27
 *
28
 * This program is distributed in the hope that it will be useful,
29
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
30
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
31
 * GNU Affero General Public License for more details.
32
 *
33
 * You should have received a copy of the GNU Affero General Public License
34
 * along with this program. If not, see <http://www.gnu.org/licenses/>.
35
 */
36
37
class Model extends DispatcherClassModel {
38
39
    use TimestampTrait;
40
41
    private $bypass = false;
42
    
43
    private $route = null;
44
45
    private $cache;
46
47
    private $request;
48
49
    private $response;
50
51
    private $table;
52
53
    public function __construct(
54
        Configuration $configuration,
55
        Logger $logger,
56
        CacheManager $cache,
57
        Extra $extra = null
58
    ) {
59
60
        parent::__construct($configuration, $logger);
61
62
        $this->table = new Table($cache, $configuration, $logger);
63
64
        $this->cache = $cache;
65
66
        $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...
67
68
        $this->setTimestamp();
69
70
    }
71
72
    public function table() {
73
74
        return $this->table;
75
76
    }
77
78
    public function bypass($mode = true) {
79
80
        $this->bypass = filter_var($mode, FILTER_VALIDATE_BOOLEAN);
81
82
        return $this;
83
84
    }
85
86
    public function route(Request $request) {
87
88
        $method = $request->method()->get();
89
90
        $methods = $this->configuration->get('allowed-http-methods');
91
92
        if ( ( $methods != null || !empty($methods) ) && in_array($method, $methods) === false ) {
93
94
            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...
95
                "Allow" => implode(",",$methods)
96
            ));
97
98
        }
99
100
        $this->request = $request;
101
102
        if (!$this->parse()) {
103
104
            throw new DispatcherException("Unable to find a valid route for the specified uri", 0, null, 404);
105
106
        } else {
107
            
108
            return $this->route;
109
            
110
        }
111
112
    }
113
114
    public function compose(Response $response) {
115
116
        $this->response = $response;
117
        
118
        if (is_null($this->route)) {
119
            
120
            throw new DispatcherException("Route has not been loaded!");
121
            
122
        }
123
124
        $service = $this->route->getInstance(
125
            $this->request,
126
            $this->response,
127
            $this->extra
128
        );
129
130
        if (!is_null($service)) {
131
132
            $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...
133
134
            $method = $this->request->method()->get();
135
136
            $methods = $service->getImplementedMethods();
137
138
            if ( in_array($method, $methods) ) {
139
140
                $callable = $service->getMethod($method);
141
142
                try {
143
144
                    $result = call_user_func(array($service, $callable));
145
146
                } catch (DispatcherException $de) {
147
148
                    throw new DispatcherException(sprintf("Service '%s' exception for method '%s': %s", $this->service, $method, $de->getMessage()), 0, $de, 500);
0 ignored issues
show
Bug introduced by
The property service 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...
149
150
                } catch (Exception $e) {
151
152
                    throw new DispatcherException(sprintf("Service '%s' execution failed for method '%s': %s", $this->service, $method, $e->getMessage()), 0, $e, 500);
153
154
                }
155
156
            } else {
157
158
                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...
159
                    "Allow" => implode(",", $methods)
160
                ));
161
162
            }
163
164
            $this->response->content()->set($result);
165
166
        } else {
167
168
            throw new DispatcherException(sprintf("Unable to execute service '%s'", $this->service), 0, null, 500);
169
170
        }
171
172
    }
173
174
    private function parse() {
175
176
        $path = $this->request->route();
177
        
178
        foreach ($this->table->routes() as $regex => $value) {
0 ignored issues
show
Bug introduced by
The expression $this->table->routes() of type array|object<Comodojo\Dispatcher\Router\Table> 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...
179
            
180
            // The current uri is checked against all the global regular expressions associated with the routes
181
            if (preg_match("/" . $regex . "/", $path, $matches)) {
182
183
                /* If a route is matched, all the bits of the route string are evalued in order to create
184
                 * new query parameters which will be available for the service class
185
                 */
186
                $this->evalUri($value['query'], $matches);
187
188
                // All the route parameters are also added to the query parameters
189
                foreach ($value['parameters'] as $parameter => $value) {
190
191
                    $this->request->query()->set($parameter, $value);
192
193
                }
194
                
195
                $service = implode('.', $value['service']);
196
                
197
                $this->route = new Route($this);
198
                
199
                $this->route->setClassName($value['class']);
200
                $this->route->setType($value['type']);
201
                $this->route->setService(empty($service)?"default":$service);
202
203
                return true;
204
205
            }
206
207
        }
208
209
        return false;
210
211
    }
212
213
    private function evalUri($parameters, $bits) {
214
215
        $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...
216
217
        // Because of the nature of the global regular expression, all the bits of the matched route are associated with a parameter key
218
        foreach ($parameters as $key => $value) {
219
220
            if (isset($bits[$key])) {
221
                /* if it's available a bit associated with the parameter name, it is compared against
222
                 * it's regular expression in order to extrect backreferences
223
                 */
224
                if (preg_match('/^' . $value['regex'] . '$/', $bits[$key], $matches)) {
225
                    
226
                    if (count($matches) == 1) $matches = $matches[0]; // This is the case where no backreferences are present or available.
227
                    
228
                    // The extracted value (with any backreference available) is added to the query parameters.
229
                    $this->request->query()->set($key, $matches);
230
231
                }
232
233
            } elseif ($value['required']) {
234
235
                throw new DispatcherException(sprintf("Required parameter '%s' not specified.", $key), 1, null, 500);
236
237
            }
238
239
        }
240
241
    }
242
243
}
244