Completed
Push — 4.0 ( 6a2270...a7534e )
by Marco
12:55
created

Model::parse()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 23
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Importance

Changes 2
Bugs 0 Features 1
Metric Value
c 2
b 0
f 1
dl 0
loc 23
rs 9.0856
cc 3
eloc 7
nc 3
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\Router\Route;
6
use \Comodojo\Dispatcher\Components\Timestamp as TimestampTrait;
7
use \Comodojo\Dispatcher\Request\Model as Request;
8
use \Comodojo\Dispatcher\Response\Model as Response;
9
use \Comodojo\Dispatcher\Extra\Model as Extra;
10
use \Comodojo\Dispatcher\Components\Configuration;
11
use \Comodojo\Cache\CacheManager;
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 Model extends DispatcherClassModel {
39
40
    use TimestampTrait;
41
42
    private $bypass = false;
43
    
44
    private $route = null;
45
46
    private $cache;
47
48
    private $request;
49
50
    private $response;
51
52
    private $table;
53
54
    public function __construct(
55
        Configuration $configuration,
56
        Logger $logger,
57
        CacheManager $cache,
58
        Extra $extra = null
59
    ) {
60
61
        parent::__construct($configuration, $logger);
62
63
        $this->table = new Table($cache, $this);
64
65
        $this->cache = $cache;
66
67
        $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...
68
69
        $this->setTimestamp();
70
71
    }
72
73
    public function table() {
74
75
        return $this->table;
76
77
    }
78
79
    public function bypass(Route $route) {
80
81
        $this->bypass = true;
82
        
83
        $this->route = $route;
84
85
        return $this;
86
87
    }
88
89
    public function route(Request $request) {
90
91
        $method = $request->method()->get();
92
93
        $methods = $this->configuration->get('allowed-http-methods');
94
95
        if ( ( $methods != null || !empty($methods) ) && in_array($method, $methods) === false ) {
96
97
            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...
98
                "Allow" => implode(",",$methods)
99
            ));
100
101
        }
102
103
        $this->request = $request;
104
105
        if (!$this->bypass) {
106
            
107
            if (!$this->parse()) throw new DispatcherException("Unable to find a valid route for the specified uri", 0, null, 404);
108
109
        }
110
        
111
        return $this->route;
112
113
    }
114
115
    public function compose(Response $response) {
116
117
        $this->response = $response;
118
        
119
        if (is_null($this->route)) {
120
            
121
            throw new DispatcherException("Route has not been loaded!");
122
            
123
        }
124
125
        $service = $this->route->getInstance(
126
            $this->request,
127
            $this->response,
128
            $this->extra
129
        );
130
131
        if (!is_null($service)) {
132
133
            $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...
134
135
            $method = $this->request->method()->get();
136
137
            $methods = $service->getImplementedMethods();
138
139
            if ( in_array($method, $methods) ) {
140
141
                $callable = $service->getMethod($method);
142
143
                try {
144
145
                    $result = call_user_func(array($service, $callable));
146
147
                } catch (DispatcherException $de) {
148
149
                    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...
150
151
                } catch (Exception $e) {
152
153
                    throw new DispatcherException(sprintf("Service '%s' execution failed for method '%s': %s", $this->service, $method, $e->getMessage()), 0, $e, 500);
154
155
                }
156
157
            } else {
158
159
                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...
160
                    "Allow" => implode(",", $methods)
161
                ));
162
163
            }
164
165
            $this->response->content()->set($result);
166
167
        } else {
168
169
            throw new DispatcherException(sprintf("Unable to execute service '%s'", $this->service), 0, null, 500);
170
171
        }
172
173
    }
174
175
    private function parse() {
176
177
        $path = $this->request->route();
178
        
179
        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...
180
            
181
            // The current uri is checked against all the global regular expressions associated with the routes
182
            if (preg_match("/" . $regex . "/", $path, $matches)) {
183
184
                /* If a route is matched, all the bits of the route string are evalued in order to create
185
                 * new query parameters which will be available for the service class
186
                 */
187
                $this->route = $value->path($matches);
188
189
                return true;
190
191
            }
192
193
        }
194
195
        return false;
196
197
    }
198
199
}
200