Completed
Push — 4.0 ( 89799b...3c6496 )
by Marco
02:53
created

Model::getRoute()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 5
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 5
rs 9.4285
cc 1
eloc 2
nc 1
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 \Psr\Log\LoggerInterface;
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_routing = false;
43
    
44
    private $bypass_service = false;
45
    
46
    private $route;
47
48
    private $cache;
49
50
    private $request;
51
52
    private $response;
53
54
    private $table;
55
56
    public function __construct(
57
        Configuration $configuration,
58
        LoggerInterface $logger,
59
        CacheManager $cache,
60
        Extra $extra
61
    ) {
62
63
        parent::__construct($configuration, $logger);
64
65
        $this->table = new Table($cache, $this);
66
67
        $this->cache = $cache;
68
69
        $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...
70
71
        $this->setTimestamp();
72
73
    }
74
75
    public function table() {
76
77
        return $this->table;
78
79
    }
80
81
    public function bypassRouting(Route $route) {
82
83
        $this->bypass_routing = true;
84
        
85
        $this->route = $route;
86
87
        return $this;
88
89
    }
90
    
91
    public function bypassService() {
92
93
        $this->bypass_service = true;
94
95
        return $this;
96
97
    }
98
99
    public function getRoute() {
100
101
        return $this->route;
102
103
    }
104
105
    public function route(Request $request) {
106
107
        $method = $request->method()->get();
108
109
        $methods = $this->configuration->get('allowed-http-methods');
110
111
        if ( ( $methods != null || !empty($methods) ) && in_array($method, $methods) === false ) {
112
113
            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...
114
                "Allow" => implode(",",$methods)
115
            ));
116
117
        }
118
119
        $this->request = $request;
120
121
        if (!$this->bypass_routing) {
122
            
123
            if (!$this->parse()) throw new DispatcherException("Unable to find a valid route for the specified uri", 0, null, 404);
124
125
        }
126
        
127
        return $this->route;
128
129
    }
130
131
    public function compose(Response $response) {
132
133
        $this->response = $response;
134
        
135
        if (is_null($this->route)) {
136
            
137
            throw new DispatcherException("Route has not been loaded!");
138
            
139
        }
140
        
141
        if ( $this->bypass_service ) {
142
            
143
            return;
144
            
145
        }
146
147
        $service = $this->route->getInstance(
148
            $this->request,
149
            $this->response,
150
            $this->extra
151
        );
152
153
        if (!is_null($service)) {
154
155
            $result = "";
156
157
            $method = $this->request->method()->get();
158
159
            $methods = $service->getImplementedMethods();
160
161
            if ( in_array($method, $methods) ) {
162
163
                $callable = $service->getMethod($method);
164
165
                try {
166
167
                    $result = call_user_func(array($service, $callable));
168
169
                } catch (DispatcherException $de) {
170
171
                    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 seem to exist. Did you mean bypass_service?

An attempt at access to an undefined property has been detected. This may either be a typographical error or the property has been renamed but there are still references to its old name.

If you really want to allow access to undefined properties, you can define magic methods to allow access. See the php core documentation on Overloading.

Loading history...
172
173
                } catch (Exception $e) {
174
175
                    throw new DispatcherException(sprintf("Service '%s' execution failed for method '%s': %s", $this->service, $method, $e->getMessage()), 0, $e, 500);
0 ignored issues
show
Bug introduced by
The property service does not seem to exist. Did you mean bypass_service?

An attempt at access to an undefined property has been detected. This may either be a typographical error or the property has been renamed but there are still references to its old name.

If you really want to allow access to undefined properties, you can define magic methods to allow access. See the php core documentation on Overloading.

Loading history...
176
177
                }
178
179
            } else {
180
181
                throw new DispatcherException(sprintf("Service '%s' doesn't implement method '%s'", $this->route->getServiceName(), $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...
182
                    "Allow" => implode(",", $methods)
183
                ));
184
185
            }
186
187
            $this->response->content()->set($result);
188
189
        } else {
190
191
            throw new DispatcherException(sprintf("Unable to execute service '%s'", $this->service), 0, null, 500);
0 ignored issues
show
Bug introduced by
The property service does not seem to exist. Did you mean bypass_service?

An attempt at access to an undefined property has been detected. This may either be a typographical error or the property has been renamed but there are still references to its old name.

If you really want to allow access to undefined properties, you can define magic methods to allow access. See the php core documentation on Overloading.

Loading history...
192
193
        }
194
195
    }
196
197
    private function parse() {
198
199
        $path = $this->request->route();
200
        
201
        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...
202
            
203
            // The current uri is checked against all the global regular expressions associated with the routes
204
            if (preg_match("/" . $regex . "/", $path, $matches)) {
205
206
                /* If a route is matched, all the bits of the route string are evalued in order to create
207
                 * new query parameters which will be available for the service class
208
                 */
209
                $this->route = $value->path($matches);
210
211
                return true;
212
213
            }
214
215
        }
216
217
        return false;
218
219
    }
220
221
}
222