GitHub Access Token became invalid

It seems like the GitHub access token used for retrieving details about this repository from GitHub became invalid. This might prevent certain types of inspections from being run (in particular, everything related to pull requests).
Please ask an admin of your repository to re-new the access token on this website.
Completed
Push — 3.x ( 768a94...89c014 )
by
unknown
19s
created

Router::fullUrlFor()   A

Complexity

Conditions 3
Paths 4

Size

Total Lines 9

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 9
rs 9.9666
c 0
b 0
f 0
cc 3
nc 4
nop 4
1
<?php
2
/**
3
 * Slim Framework (https://slimframework.com)
4
 *
5
 * @link      https://github.com/slimphp/Slim
6
 * @copyright Copyright (c) 2011-2017 Josh Lockhart
7
 * @license   https://github.com/slimphp/Slim/blob/3.x/LICENSE.md (MIT License)
8
 */
9
namespace Slim;
10
11
use FastRoute\Dispatcher;
12
use Psr\Container\ContainerInterface;
13
use InvalidArgumentException;
14
use Psr\Http\Message\UriInterface;
15
use RuntimeException;
16
use Psr\Http\Message\ServerRequestInterface;
17
use FastRoute\RouteCollector;
18
use FastRoute\RouteParser;
19
use FastRoute\RouteParser\Std as StdParser;
20
use Slim\Interfaces\RouteGroupInterface;
21
use Slim\Interfaces\RouterInterface;
22
use Slim\Interfaces\RouteInterface;
23
24
/**
25
 * Router
26
 *
27
 * This class organizes Slim application route objects. It is responsible
28
 * for registering route objects, assigning names to route objects,
29
 * finding routes that match the current HTTP request, and creating
30
 * URLs for a named route.
31
 */
32
class Router implements RouterInterface
33
{
34
    /**
35
     * Container Interface
36
     *
37
     * @var ContainerInterface
38
     */
39
    protected $container;
40
41
    /**
42
     * Parser
43
     *
44
     * @var \FastRoute\RouteParser
45
     */
46
    protected $routeParser;
47
48
    /**
49
     * Base path used in pathFor()
50
     *
51
     * @var string
52
     */
53
    protected $basePath = '';
54
55
    /**
56
     * Path to fast route cache file. Set to false to disable route caching
57
     *
58
     * @var string|False
59
     */
60
    protected $cacheFile = false;
61
62
    /**
63
     * Routes
64
     *
65
     * @var Route[]
66
     */
67
    protected $routes = [];
68
69
    /**
70
     * Route counter incrementer
71
     * @var int
72
     */
73
    protected $routeCounter = 0;
74
75
    /**
76
     * Route groups
77
     *
78
     * @var RouteGroup[]
79
     */
80
    protected $routeGroups = [];
81
82
    /**
83
     * @var \FastRoute\Dispatcher
84
     */
85
    protected $dispatcher;
86
87
    /**
88
     * Create new router
89
     *
90
     * @param RouteParser   $parser
91
     */
92
    public function __construct(RouteParser $parser = null)
93
    {
94
        $this->routeParser = $parser ?: new StdParser;
95
    }
96
97
    /**
98
     * Set the base path used in pathFor()
99
     *
100
     * @param string $basePath
101
     *
102
     * @return self
103
     */
104
    public function setBasePath($basePath)
105
    {
106
        if (!is_string($basePath)) {
107
            throw new InvalidArgumentException('Router basePath must be a string');
108
        }
109
110
        $this->basePath = $basePath;
111
112
        return $this;
113
    }
114
115
    /**
116
     * Get the base path used in pathFor()
117
     *
118
     * @return string
119
     */
120
    public function getBasePath()
121
    {
122
        return $this->basePath;
123
    }
124
125
    /**
126
     * Set path to fast route cache file. If this is false then route caching is disabled.
127
     *
128
     * @param string|false $cacheFile
129
     *
130
     * @return self
131
     */
132
    public function setCacheFile($cacheFile)
133
    {
134
        if (!is_string($cacheFile) && $cacheFile !== false) {
135
            throw new InvalidArgumentException('Router cache file must be a string or false');
136
        }
137
138
        if ($cacheFile && file_exists($cacheFile) && !is_readable($cacheFile)) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $cacheFile of type string|false is loosely compared to true; this is ambiguous if the string can be empty. You might want to explicitly use !== false instead.

In PHP, under loose comparison (like ==, or !=, or switch conditions), values of different types might be equal.

For string values, the empty string '' is a special case, in particular the following results might be unexpected:

''   == false // true
''   == null  // true
'ab' == false // false
'ab' == null  // false

// It is often better to use strict comparison
'' === false // false
'' === null  // false
Loading history...
139
            throw new RuntimeException(
140
                sprintf('Router cache file `%s` is not readable', $cacheFile)
141
            );
142
        }
143
144
        if ($cacheFile && !file_exists($cacheFile) && !is_writable(dirname($cacheFile))) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $cacheFile of type string|false is loosely compared to true; this is ambiguous if the string can be empty. You might want to explicitly use !== false instead.

In PHP, under loose comparison (like ==, or !=, or switch conditions), values of different types might be equal.

For string values, the empty string '' is a special case, in particular the following results might be unexpected:

''   == false // true
''   == null  // true
'ab' == false // false
'ab' == null  // false

// It is often better to use strict comparison
'' === false // false
'' === null  // false
Loading history...
145
            throw new RuntimeException(
146
                sprintf('Router cache file directory `%s` is not writable', dirname($cacheFile))
147
            );
148
        }
149
150
        $this->cacheFile = $cacheFile;
151
        return $this;
152
    }
153
154
    /**
155
     * @param ContainerInterface $container
156
     */
157
    public function setContainer(ContainerInterface $container)
158
    {
159
        $this->container = $container;
160
    }
161
162
    /**
163
     * Add route
164
     *
165
     * @param  string[] $methods Array of HTTP methods
166
     * @param  string   $pattern The route pattern
167
     * @param  callable $handler The route callable
168
     *
169
     * @return RouteInterface
170
     *
171
     * @throws InvalidArgumentException if the route pattern isn't a string
172
     */
173
    public function map($methods, $pattern, $handler)
174
    {
175
        if (!is_string($pattern)) {
176
            throw new InvalidArgumentException('Route pattern must be a string');
177
        }
178
179
        // Prepend parent group pattern(s)
180
        if ($this->routeGroups) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $this->routeGroups of type Slim\RouteGroup[] is implicitly converted to a boolean; are you sure this is intended? If so, consider using ! empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
181
            $pattern = $this->processGroups() . $pattern;
182
        }
183
184
        // According to RFC methods are defined in uppercase (See RFC 7231)
185
        $methods = array_map("strtoupper", $methods);
186
187
        /** @var \Slim\Route */
188
        $route = $this->createRoute($methods, $pattern, $handler);
189
        // Add route
190
        $this->routes[$route->getIdentifier()] = $route;
191
        $this->routeCounter++;
192
193
        return $route;
194
    }
195
196
    /**
197
     * Dispatch router for HTTP request
198
     *
199
     * @param  ServerRequestInterface $request The current HTTP request object
200
     *
201
     * @return array
202
     *
203
     * @link   https://github.com/nikic/FastRoute/blob/master/src/Dispatcher.php
204
     */
205
    public function dispatch(ServerRequestInterface $request)
206
    {
207
        $uri = '/' . ltrim($request->getUri()->getPath(), '/');
208
209
        return $this->createDispatcher()->dispatch(
210
            $request->getMethod(),
211
            $uri
212
        );
213
    }
214
215
    /**
216
     * Create a new Route object
217
     *
218
     * @param  string[] $methods Array of HTTP methods
219
     * @param  string   $pattern The route pattern
220
     * @param  callable $callable The route callable
221
     *
222
     * @return \Slim\Interfaces\RouteInterface
223
     */
224
    protected function createRoute($methods, $pattern, $callable)
225
    {
226
        $route = new Route($methods, $pattern, $callable, $this->routeGroups, $this->routeCounter);
227
        if (!empty($this->container)) {
228
            $route->setContainer($this->container);
229
        }
230
231
        return $route;
232
    }
233
234
    /**
235
     * @return \FastRoute\Dispatcher
236
     */
237
    protected function createDispatcher()
238
    {
239
        if ($this->dispatcher) {
240
            return $this->dispatcher;
241
        }
242
243
        $routeDefinitionCallback = function (RouteCollector $r) {
244
            foreach ($this->getRoutes() as $route) {
245
                $r->addRoute($route->getMethods(), $route->getPattern(), $route->getIdentifier());
246
            }
247
        };
248
249
        if ($this->cacheFile) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $this->cacheFile of type string|false is loosely compared to true; this is ambiguous if the string can be empty. You might want to explicitly use !== false instead.

In PHP, under loose comparison (like ==, or !=, or switch conditions), values of different types might be equal.

For string values, the empty string '' is a special case, in particular the following results might be unexpected:

''   == false // true
''   == null  // true
'ab' == false // false
'ab' == null  // false

// It is often better to use strict comparison
'' === false // false
'' === null  // false
Loading history...
250
            $this->dispatcher = \FastRoute\cachedDispatcher($routeDefinitionCallback, [
251
                'routeParser' => $this->routeParser,
252
                'cacheFile' => $this->cacheFile,
253
            ]);
254
        } else {
255
            $this->dispatcher = \FastRoute\simpleDispatcher($routeDefinitionCallback, [
256
                'routeParser' => $this->routeParser,
257
            ]);
258
        }
259
260
        return $this->dispatcher;
261
    }
262
263
    /**
264
     * @param \FastRoute\Dispatcher $dispatcher
265
     */
266
    public function setDispatcher(Dispatcher $dispatcher)
267
    {
268
        $this->dispatcher = $dispatcher;
269
    }
270
271
    /**
272
     * Get route objects
273
     *
274
     * @return Route[]
275
     */
276
    public function getRoutes()
277
    {
278
        return $this->routes;
279
    }
280
281
    /**
282
     * Get named route object
283
     *
284
     * @param string $name        Route name
285
     *
286
     * @return Route
287
     *
288
     * @throws RuntimeException   If named route does not exist
289
     */
290
    public function getNamedRoute($name)
291
    {
292
        foreach ($this->routes as $route) {
293
            if ($name == $route->getName()) {
294
                return $route;
295
            }
296
        }
297
        throw new RuntimeException('Named route does not exist for name: ' . $name);
298
    }
299
300
    /**
301
     * Remove named route
302
     *
303
     * @param string $name        Route name
304
     *
305
     * @throws RuntimeException   If named route does not exist
306
     */
307
    public function removeNamedRoute($name)
308
    {
309
        $route = $this->getNamedRoute($name);
310
311
        // no exception, route exists, now remove by id
312
        unset($this->routes[$route->getIdentifier()]);
313
    }
314
315
    /**
316
     * Process route groups
317
     *
318
     * @return string A group pattern to prefix routes with
319
     */
320
    protected function processGroups()
321
    {
322
        $pattern = "";
323
        foreach ($this->routeGroups as $group) {
324
            $pattern .= $group->getPattern();
325
        }
326
        return $pattern;
327
    }
328
329
    /**
330
     * Add a route group to the array
331
     *
332
     * @param string   $pattern
333
     * @param callable $callable
334
     *
335
     * @return RouteGroupInterface
336
     */
337
    public function pushGroup($pattern, $callable)
338
    {
339
        $group = new RouteGroup($pattern, $callable);
340
        array_push($this->routeGroups, $group);
341
        return $group;
342
    }
343
344
    /**
345
     * Removes the last route group from the array
346
     *
347
     * @return RouteGroup|bool The RouteGroup if successful, else False
348
     */
349
    public function popGroup()
350
    {
351
        $group = array_pop($this->routeGroups);
352
        return $group instanceof RouteGroup ? $group : false;
0 ignored issues
show
Bug Compatibility introduced by
The expression $group instanceof \Slim\...Group ? $group : false; of type Slim\RouteGroup|false adds the type Slim\RouteGroup to the return on line 352 which is incompatible with the return type declared by the interface Slim\Interfaces\RouterInterface::popGroup of type boolean.
Loading history...
353
    }
354
355
    /**
356
     *
357
     * @param string $identifier
358
     * @return \Slim\Interfaces\RouteInterface
359
     */
360
    public function lookupRoute($identifier)
361
    {
362
        if (!isset($this->routes[$identifier])) {
363
            throw new RuntimeException('Route not found, looks like your route cache is stale.');
364
        }
365
        return $this->routes[$identifier];
366
    }
367
368
    /**
369
     * Build the path for a named route excluding the base path
370
     *
371
     * @param string $name        Route name
372
     * @param array  $data        Named argument replacement data
373
     * @param array  $queryParams Optional query string parameters
374
     *
375
     * @return string
376
     *
377
     * @throws RuntimeException         If named route does not exist
378
     * @throws InvalidArgumentException If required data not provided
379
     */
380
    public function relativePathFor($name, array $data = [], array $queryParams = [])
381
    {
382
        $route = $this->getNamedRoute($name);
383
        $pattern = $route->getPattern();
384
385
        $routeDatas = $this->routeParser->parse($pattern);
386
        // $routeDatas is an array of all possible routes that can be made. There is
387
        // one routedata for each optional parameter plus one for no optional parameters.
388
        //
389
        // The most specific is last, so we look for that first.
390
        $routeDatas = array_reverse($routeDatas);
391
392
        $segments = [];
393
        $segmentName = '';
394
        foreach ($routeDatas as $routeData) {
395
            foreach ($routeData as $item) {
396
                if (is_string($item)) {
397
                    // this segment is a static string
398
                    $segments[] = $item;
399
                    continue;
400
                }
401
402
                // This segment has a parameter: first element is the name
403
                if (!array_key_exists($item[0], $data)) {
404
                    // we don't have a data element for this segment: cancel
405
                    // testing this routeData item, so that we can try a less
406
                    // specific routeData item.
407
                    $segments = [];
408
                    $segmentName = $item[0];
409
                    break;
410
                }
411
                $segments[] = $data[$item[0]];
412
            }
413
            if (!empty($segments)) {
414
                // we found all the parameters for this route data, no need to check
415
                // less specific ones
416
                break;
417
            }
418
        }
419
420
        if (empty($segments)) {
421
            throw new InvalidArgumentException('Missing data for URL segment: ' . $segmentName);
422
        }
423
        $url = implode('', $segments);
424
425
        if ($queryParams) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $queryParams of type array is implicitly converted to a boolean; are you sure this is intended? If so, consider using ! empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
426
            $url .= '?' . http_build_query($queryParams);
427
        }
428
429
        return $url;
430
    }
431
432
433
    /**
434
     * Build the path for a named route including the base path
435
     *
436
     * This method will be deprecated in Slim 4. Use urlFor() from now on.
437
     *
438
     * @param string $name        Route name
439
     * @param array  $data        Named argument replacement data
440
     * @param array  $queryParams Optional query string parameters
441
     *
442
     * @return string
443
     *
444
     * @throws RuntimeException         If named route does not exist
445
     * @throws InvalidArgumentException If required data not provided
446
     */
447
    public function pathFor($name, array $data = [], array $queryParams = [])
448
    {
449
        return $this->urlFor($name, $data, $queryParams);
450
    }
451
452
    /**
453
     * Build the path for a named route including the base path
454
     *
455
     * @param string $name        Route name
456
     * @param array  $data        Named argument replacement data
457
     * @param array  $queryParams Optional query string parameters
458
     *
459
     * @return string
460
     *
461
     * @throws RuntimeException         If named route does not exist
462
     * @throws InvalidArgumentException If required data not provided
463
     */
464
    public function urlFor($name, array $data = [], array $queryParams = [])
465
    {
466
        $url = $this->relativePathFor($name, $data, $queryParams);
467
468
        if ($this->basePath) {
469
            $url = $this->basePath . $url;
470
        }
471
472
        return $url;
473
    }
474
475
    /**
476
     * Get fully qualified URL for named route
477
     *
478
     * @param UriInterface $uri
479
     * @param string $routeName
480
     * @param array $data Named argument replacement data
481
     * @param array $queryParams Optional query string parameters
482
     *
483
     * @return string
484
     *
485
     */
486
    public function fullUrlFor(UriInterface $uri, $routeName, array $data = [], array $queryParams = [])
487
    {
488
        $path = $this->urlFor($routeName, $data, $queryParams);
489
        $scheme = $uri->getScheme();
490
        $authority = $uri->getAuthority();
491
        $protocol = ($scheme ? $scheme . ':' : '') . ($authority ? '//' . $authority : '');
492
493
        return $protocol . $path;
494
    }
495
}
496