Completed
Push — master ( f97d4a...febe27 )
by Mikael
02:45
created

Router::handleInternal()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 9
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 6

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 9
ccs 0
cts 7
cp 0
rs 9.6666
cc 2
eloc 6
nc 2
nop 1
crap 6
1
<?php
2
3
namespace Anax\Route;
4
5
use Anax\DI\InjectionAwareInterface;
6
use Anax\DI\InjectionAwareTrait;
7
use \Anax\Configure\ConfigureInterface;
8
use \Anax\Configure\ConfigureTrait;
9
10
/**
11
 * A container for routes.
12
 */
13
class Router implements
14
    InjectionAwareInterface,
15
    ConfigureInterface
16
{
17
    use InjectionAwareTrait;
18
    use ConfigureTrait {
19
        configure as protected loadConfiguration;
20
    }
21
22
23
24
    /**
25
     * @var array       $routes         all the routes.
26
     * @var array       $internalRoutes all internal routes.
27
     * @var null|string $lastRoute      last route that was matched and called.
28
     */
29
    private $routes         = [];
30
    private $internalRoutes = [];
31
    private $lastRoute      = null;
32
33
34
35
    /**
36
     * Load and apply configurations.
37
     *
38
     * @param array|string $what is an array with key/value config options
39
     *                           or a file to be included which returns such
40
     *                           an array.
41
     *
42
     * @throws Anax\Configure\Exception when template file is missing
43
     *
44
     * @return string as path to the template file
45
     */
46
    public function configure($what)
47
    {
48
        $this->loadConfiguration($what);
49
50
        $includes = $this->getConfig("include", []);
0 ignored issues
show
Documentation introduced by
array() is of type array, but the function expects a string|null.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
51
        foreach ($includes as $include) {
52
            require $include;
53
        }
54
    }
55
56
57
58
    /**
59
     * Handle the routes and match them towards the request, dispatch them
60
     * when a match is made. Each route handler may throw exceptions that
61
     * may redirect to an internal route for error handling.
62
     * Several routes can match and if the routehandler does not break
63
     * execution flow, the route matching will carry on.
64
     * Only the last routehandler will get its return value returned further.
65
     *
66
     * @param string $path    the path to find a matching handler for.
67
     * @param string $method  the request method to match.
68
     *
69
     * @return mixed content returned from route.
70
     */
71
    public function handle($path, $method = null)
72
    {
73
        try {
74
            $match = false;
75
            foreach ($this->routes as $route) {
76
                if ($route->match($path, $method)) {
77
                    $this->lastRoute = $route->getRule();
78
                    $match = true;
79
                    $results = $route->handle($this->di);
80
                }
81
            }
82
83
            if ($match) {
84
                return $results;
0 ignored issues
show
Bug introduced by
The variable $results does not seem to be defined for all execution paths leading up to this point.

If you define a variable conditionally, it can happen that it is not defined for all execution paths.

Let’s take a look at an example:

function myFunction($a) {
    switch ($a) {
        case 'foo':
            $x = 1;
            break;

        case 'bar':
            $x = 2;
            break;
    }

    // $x is potentially undefined here.
    echo $x;
}

In the above example, the variable $x is defined if you pass “foo” or “bar” as argument for $a. However, since the switch statement has no default case statement, if you pass any other value, the variable $x would be undefined.

Available Fixes

  1. Check for existence of the variable explicitly:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        if (isset($x)) { // Make sure it's always set.
            echo $x;
        }
    }
    
  2. Define a default value for the variable:

    function myFunction($a) {
        $x = ''; // Set a default which gets overridden for certain paths.
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        echo $x;
    }
    
  3. Add a value for the missing path:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
    
            // We add support for the missing case.
            default:
                $x = '';
                break;
        }
    
        echo $x;
    }
    
Loading history...
85
            }
86
87
            $this->handleInternal("404");
88
        } catch (ForbiddenException $e) {
89
            $this->handleInternal("403");
90
        } catch (NotFoundException $e) {
91
            $this->handleInternal("404");
92
        } catch (InternalErrorException $e) {
93
            $this->handleInternal("500");
94
        }
95
    }
96
97
98
99
    /**
100
     * Handle an internal route, the internal routes are not exposed to the
101
     * end user.
102
     *
103
     * @param string $rule for this route.
104
     *
105
     * @return void
106
     *
107
     * @throws \Anax\Route\NotFoundException
108
     */
109
    public function handleInternal($rule)
110
    {
111
        if (!isset($this->internalRoutes[$rule])) {
112
            throw new NotFoundException("No internal route to handle: " . $rule);
113
        }
114
        $route = $this->internalRoutes[$rule];
115
        $this->lastRoute = $rule;
116
        $route->handle();
117
    }
118
119
120
121
    /**
122
     * Load routes from a config file, the file should return an array with
123
     * routes.
124
     *
125
     * @param string $file to load routes from.
126
     *
127
     * @return self
128
     */
129
    public function load($file)
130
    {
131
        $config = require $file;
132
        foreach ($config["routes"] as $route) {
133
            $this->any(
134
                $route["requestMethod"],
135
                $route["path"],
136
                $route["callable"]
137
            );
138
        }
139
        return $this;
140
    }
141
142
143
144
    /**
145
     * Add a route with a request method, a path rule to match and an action
146
     * as the callback. Adding several path rules (array) results in several
147
     * routes being created.
148
     *
149
     * @param null|string|array    $method as a valid request method.
150
     * @param null|string|array    $rule   path rule for this route.
151
     * @param null|string|callable $action to implement a handler for the route.
152
     * @param null|string          $info   about the route.
153
     *
154
     * @return class|array as new route(s), class if one added, else array.
155
     */
156
    public function any($method, $rule, $action, $info = null)
157
    {
158
        $rules = is_array($rule) ? $rule : [$rule];
159
160
        $routes = [];
161
        foreach ($rules as $val) {
162
            $route = new Route();
163
            $route->set($val, $action, $method, $info);
164
            $routes[] = $route;
165
            $this->routes[] = $route;
166
        }
167
168
        return count($routes) === 1 ? $routes[0] : $routes;
169
    }
170
171
172
173
    /**
174
     * Add a route to the router by rule(s) and a callback.
175
     *
176
     * @param null|string|array    $rule   for this route.
177
     * @param null|string|callable $action a callback handler for the route.
178
     *
179
     * @return class|array as new route(s), class if one added, else array.
180
     */
181
    public function add($rule, $action = null)
182
    {
183
        return $this->any(null, $rule, $action);
184
    }
185
186
187
188
    /**
189
    * Add a default route which will be applied for any path.
190
     *
191
     * @param string|callable $action a callback handler for the route.
192
     *
193
     * @return class as new route.
194
     */
195
    public function always($action)
196
    {
197
        return $this->any(null, null, $action);
0 ignored issues
show
Bug Compatibility introduced by
The expression $this->any(null, null, $action); of type Anax\Route\class|array adds the type array to the return on line 197 which is incompatible with the return type documented by Anax\Route\Router::always of type Anax\Route\class.
Loading history...
198
    }
199
200
201
202
    /**
203
     * Add a default route which will be applied for any path, if the choosen
204
     * request method is matching.
205
     *
206
     * @param null|string|array    $method as request methods
207
     * @param null|string|callable $action a callback handler for the route.
208
     *
209
     * @return class|array as new route(s), class if one added, else array.
210
     */
211
    public function all($method, $action)
212
    {
213
        return $this->any($method, null, $action);
214
    }
215
216
217
218
    /**
219
     * Shortcut to add a GET route.
220
     *
221
     * @param null|string|array    $method as request methods
0 ignored issues
show
Bug introduced by
There is no parameter named $method. Was it maybe removed?

This check looks for PHPDoc comments describing methods or function parameters that do not exist on the corresponding method or function.

Consider the following example. The parameter $italy is not defined by the method finale(...).

/**
 * @param array $germany
 * @param array $island
 * @param array $italy
 */
function finale($germany, $island) {
    return "2:1";
}

The most likely cause is that the parameter was removed, but the annotation was not.

Loading history...
222
     * @param null|string|callable $action a callback handler for the route.
223
     *
224
     * @return class|array as new route(s), class if one added, else array.
225
     */
226
    public function get($rule, $action)
227
    {
228
        return $this->any(["GET"], $rule, $action);
229
    }
230
231
232
233
    /**
234
    * Shortcut to add a POST route.
235
     *
236
     * @param null|string|array    $method as request methods
0 ignored issues
show
Bug introduced by
There is no parameter named $method. Was it maybe removed?

This check looks for PHPDoc comments describing methods or function parameters that do not exist on the corresponding method or function.

Consider the following example. The parameter $italy is not defined by the method finale(...).

/**
 * @param array $germany
 * @param array $island
 * @param array $italy
 */
function finale($germany, $island) {
    return "2:1";
}

The most likely cause is that the parameter was removed, but the annotation was not.

Loading history...
237
     * @param null|string|callable $action a callback handler for the route.
238
     *
239
     * @return class|array as new route(s), class if one added, else array.
240
     */
241
    public function post($rule, $action)
242
    {
243
        return $this->any(["POST"], $rule, $action);
244
    }
245
246
247
248
    /**
249
    * Shortcut to add a PUT route.
250
     *
251
     * @param null|string|array    $method as request methods
0 ignored issues
show
Bug introduced by
There is no parameter named $method. Was it maybe removed?

This check looks for PHPDoc comments describing methods or function parameters that do not exist on the corresponding method or function.

Consider the following example. The parameter $italy is not defined by the method finale(...).

/**
 * @param array $germany
 * @param array $island
 * @param array $italy
 */
function finale($germany, $island) {
    return "2:1";
}

The most likely cause is that the parameter was removed, but the annotation was not.

Loading history...
252
     * @param null|string|callable $action a callback handler for the route.
253
     *
254
     * @return class|array as new route(s), class if one added, else array.
255
     */
256
    public function put($rule, $action)
257
    {
258
        return $this->any(["PUT"], $rule, $action);
259
    }
260
261
262
263
    /**
264
    * Shortcut to add a DELETE route.
265
     *
266
     * @param null|string|array    $method as request methods
0 ignored issues
show
Bug introduced by
There is no parameter named $method. Was it maybe removed?

This check looks for PHPDoc comments describing methods or function parameters that do not exist on the corresponding method or function.

Consider the following example. The parameter $italy is not defined by the method finale(...).

/**
 * @param array $germany
 * @param array $island
 * @param array $italy
 */
function finale($germany, $island) {
    return "2:1";
}

The most likely cause is that the parameter was removed, but the annotation was not.

Loading history...
267
     * @param null|string|callable $action a callback handler for the route.
268
     *
269
     * @return class|array as new route(s), class if one added, else array.
270
     */
271
    public function delete($rule, $action)
272
    {
273
        return $this->any(["DELETE"], $rule, $action);
274
    }
275
276
277
278
    /**
279
     * Add an internal route to the router, this route is not exposed to the
280
     * browser and the end user.
281
     *
282
     * @param string               $rule   for this route
283
     * @param null|string|callable $action a callback handler for the route.
284
     *
285
     * @return class|array as new route(s), class if one added, else array.
286
     */
287
    public function addInternal($rule, $action)
288
    {
289
        $route = new Route();
290
        $route->set($rule, $action);
291
        $this->internalRoutes[$rule] = $route;
292
        return $route;
293
    }
294
295
296
297
    /**
298
     * Get the route for the last route that was handled.
299
     *
300
     * @return mixed
301
     */
302
    public function getLastRoute()
303
    {
304
        return $this->lastRoute;
305
    }
306
307
308
309
    /**
310
     * Get all routes.
311
     *
312
     * @return array with all routes.
313
     */
314
    public function getAll()
315
    {
316
        return $this->routes;
317
    }
318
319
320
321
    /**
322
     * Get all internal routes.
323
     *
324
     * @return array with internal routes.
325
     */
326
    public function getInternal()
327
    {
328
        return $this->internalRoutes;
329
    }
330
}
331