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 ( 8caa5c...46229b )
by Rob
01:57
created

Router::getBasePath()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 4
rs 10
c 0
b 0
f 0
cc 1
nc 1
nop 0
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 RuntimeException;
15
use Psr\Http\Message\ServerRequestInterface;
16
use FastRoute\RouteCollector;
17
use FastRoute\RouteParser;
18
use FastRoute\RouteParser\Std as StdParser;
19
use Slim\Interfaces\RouteGroupInterface;
20
use Slim\Interfaces\RouterInterface;
21
use Slim\Interfaces\RouteInterface;
22
23
/**
24
 * Router
25
 *
26
 * This class organizes Slim application route objects. It is responsible
27
 * for registering route objects, assigning names to route objects,
28
 * finding routes that match the current HTTP request, and creating
29
 * URLs for a named route.
30
 */
31
class Router implements RouterInterface
32
{
33
    /**
34
     * Container Interface
35
     *
36
     * @var ContainerInterface
37
     */
38
    protected $container;
39
40
    /**
41
     * Parser
42
     *
43
     * @var \FastRoute\RouteParser
44
     */
45
    protected $routeParser;
46
47
    /**
48
     * Base path used in pathFor()
49
     *
50
     * @var string
51
     */
52
    protected $basePath = '';
53
54
    /**
55
     * Path to fast route cache file. Set to false to disable route caching
56
     *
57
     * @var string|False
58
     */
59
    protected $cacheFile = false;
60
61
    /**
62
     * Routes
63
     *
64
     * @var Route[]
65
     */
66
    protected $routes = [];
67
68
    /**
69
     * Route counter incrementer
70
     * @var int
71
     */
72
    protected $routeCounter = 0;
73
74
    /**
75
     * Route groups
76
     *
77
     * @var RouteGroup[]
78
     */
79
    protected $routeGroups = [];
80
81
    /**
82
     * @var \FastRoute\Dispatcher
83
     */
84
    protected $dispatcher;
85
86
    /**
87
     * Create new router
88
     *
89
     * @param RouteParser   $parser
90
     */
91
    public function __construct(RouteParser $parser = null)
92
    {
93
        $this->routeParser = $parser ?: new StdParser;
94
    }
95
96
    /**
97
     * Set the base path used in pathFor()
98
     *
99
     * @param string $basePath
100
     *
101
     * @return self
102
     */
103
    public function setBasePath($basePath)
104
    {
105
        if (!is_string($basePath)) {
106
            throw new InvalidArgumentException('Router basePath must be a string');
107
        }
108
109
        $this->basePath = $basePath;
110
111
        return $this;
112
    }
113
114
    /**
115
     * Get the base path used in pathFor()
116
     *
117
     * @return string
118
     */
119
    public function getBasePath()
120
    {
121
        return $this->basePath;
122
    }
123
124
    /**
125
     * Set path to fast route cache file. If this is false then route caching is disabled.
126
     *
127
     * @param string|false $cacheFile
128
     *
129
     * @return self
130
     */
131
    public function setCacheFile($cacheFile)
132
    {
133
        if (!is_string($cacheFile) && $cacheFile !== false) {
134
            throw new InvalidArgumentException('Router cacheFile must be a string or false');
135
        }
136
137
        $this->cacheFile = $cacheFile;
138
139
        if ($cacheFile !== false && !is_writable(dirname($cacheFile))) {
140
            throw new RuntimeException('Router cacheFile directory must be writable');
141
        }
142
143
144
        return $this;
145
    }
146
147
    /**
148
     * @param ContainerInterface $container
149
     */
150
    public function setContainer(ContainerInterface $container)
151
    {
152
        $this->container = $container;
153
    }
154
155
    /**
156
     * Add route
157
     *
158
     * @param  string[] $methods Array of HTTP methods
159
     * @param  string   $pattern The route pattern
160
     * @param  callable $handler The route callable
161
     *
162
     * @return RouteInterface
163
     *
164
     * @throws InvalidArgumentException if the route pattern isn't a string
165
     */
166
    public function map($methods, $pattern, $handler)
167
    {
168
        if (!is_string($pattern)) {
169
            throw new InvalidArgumentException('Route pattern must be a string');
170
        }
171
172
        // Prepend parent group pattern(s)
173
        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...
174
            $pattern = $this->processGroups() . $pattern;
175
        }
176
177
        // According to RFC methods are defined in uppercase (See RFC 7231)
178
        $methods = array_map("strtoupper", $methods);
179
180
        /** @var \Slim\Route */
181
        $route = $this->createRoute($methods, $pattern, $handler);
182
        // Add route
183
        $this->routes[$route->getIdentifier()] = $route;
184
        $this->routeCounter++;
185
186
        return $route;
187
    }
188
189
    /**
190
     * Dispatch router for HTTP request
191
     *
192
     * @param  ServerRequestInterface $request The current HTTP request object
193
     *
194
     * @return array
195
     *
196
     * @link   https://github.com/nikic/FastRoute/blob/master/src/Dispatcher.php
197
     */
198
    public function dispatch(ServerRequestInterface $request)
199
    {
200
        $uri = '/' . ltrim($request->getUri()->getPath(), '/');
201
202
        return $this->createDispatcher()->dispatch(
203
            $request->getMethod(),
204
            $uri
205
        );
206
    }
207
208
    /**
209
     * Create a new Route object
210
     *
211
     * @param  string[] $methods Array of HTTP methods
212
     * @param  string   $pattern The route pattern
213
     * @param  callable $callable The route callable
214
     *
215
     * @return \Slim\Interfaces\RouteInterface
216
     */
217
    protected function createRoute($methods, $pattern, $callable)
218
    {
219
        $route = new Route($methods, $pattern, $callable, $this->routeGroups, $this->routeCounter);
220
        if (!empty($this->container)) {
221
            $route->setContainer($this->container);
222
        }
223
224
        return $route;
225
    }
226
227
    /**
228
     * @return \FastRoute\Dispatcher
229
     */
230
    protected function createDispatcher()
231
    {
232
        if ($this->dispatcher) {
233
            return $this->dispatcher;
234
        }
235
236
        $routeDefinitionCallback = function (RouteCollector $r) {
237
            foreach ($this->getRoutes() as $route) {
238
                $r->addRoute($route->getMethods(), $route->getPattern(), $route->getIdentifier());
239
            }
240
        };
241
242
        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...
243
            $this->dispatcher = \FastRoute\cachedDispatcher($routeDefinitionCallback, [
244
                'routeParser' => $this->routeParser,
245
                'cacheFile' => $this->cacheFile,
246
            ]);
247
        } else {
248
            $this->dispatcher = \FastRoute\simpleDispatcher($routeDefinitionCallback, [
249
                'routeParser' => $this->routeParser,
250
            ]);
251
        }
252
253
        return $this->dispatcher;
254
    }
255
256
    /**
257
     * @param \FastRoute\Dispatcher $dispatcher
258
     */
259
    public function setDispatcher(Dispatcher $dispatcher)
260
    {
261
        $this->dispatcher = $dispatcher;
262
    }
263
264
    /**
265
     * Get route objects
266
     *
267
     * @return Route[]
268
     */
269
    public function getRoutes()
270
    {
271
        return $this->routes;
272
    }
273
274
    /**
275
     * Get named route object
276
     *
277
     * @param string $name        Route name
278
     *
279
     * @return Route
280
     *
281
     * @throws RuntimeException   If named route does not exist
282
     */
283
    public function getNamedRoute($name)
284
    {
285
        foreach ($this->routes as $route) {
286
            if ($name == $route->getName()) {
287
                return $route;
288
            }
289
        }
290
        throw new RuntimeException('Named route does not exist for name: ' . $name);
291
    }
292
293
    /**
294
     * Remove named route
295
     *
296
     * @param string $name        Route name
297
     *
298
     * @throws RuntimeException   If named route does not exist
299
     */
300
    public function removeNamedRoute($name)
301
    {
302
        $route = $this->getNamedRoute($name);
303
304
        // no exception, route exists, now remove by id
305
        unset($this->routes[$route->getIdentifier()]);
306
    }
307
308
    /**
309
     * Process route groups
310
     *
311
     * @return string A group pattern to prefix routes with
312
     */
313
    protected function processGroups()
314
    {
315
        $pattern = "";
316
        foreach ($this->routeGroups as $group) {
317
            $pattern .= $group->getPattern();
318
        }
319
        return $pattern;
320
    }
321
322
    /**
323
     * Add a route group to the array
324
     *
325
     * @param string   $pattern
326
     * @param callable $callable
327
     *
328
     * @return RouteGroupInterface
329
     */
330
    public function pushGroup($pattern, $callable)
331
    {
332
        $group = new RouteGroup($pattern, $callable);
333
        array_push($this->routeGroups, $group);
334
        return $group;
335
    }
336
337
    /**
338
     * Removes the last route group from the array
339
     *
340
     * @return RouteGroup|bool The RouteGroup if successful, else False
341
     */
342
    public function popGroup()
343
    {
344
        $group = array_pop($this->routeGroups);
345
        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 345 which is incompatible with the return type declared by the interface Slim\Interfaces\RouterInterface::popGroup of type boolean.
Loading history...
346
    }
347
348
    /**
349
     *
350
     * @param string $identifier
351
     * @return \Slim\Interfaces\RouteInterface
352
     */
353
    public function lookupRoute($identifier)
354
    {
355
        if (!isset($this->routes[$identifier])) {
356
            throw new RuntimeException('Route not found, looks like your route cache is stale.');
357
        }
358
        return $this->routes[$identifier];
359
    }
360
361
    /**
362
     * Build the path for a named route excluding the base path
363
     *
364
     * @param string $name        Route name
365
     * @param array  $data        Named argument replacement data
366
     * @param array  $queryParams Optional query string parameters
367
     *
368
     * @return string
369
     *
370
     * @throws RuntimeException         If named route does not exist
371
     * @throws InvalidArgumentException If required data not provided
372
     */
373
    public function relativePathFor($name, array $data = [], array $queryParams = [])
374
    {
375
        $route = $this->getNamedRoute($name);
376
        $pattern = $route->getPattern();
377
378
        $routeDatas = $this->routeParser->parse($pattern);
379
        // $routeDatas is an array of all possible routes that can be made. There is
380
        // one routedata for each optional parameter plus one for no optional parameters.
381
        //
382
        // The most specific is last, so we look for that first.
383
        $routeDatas = array_reverse($routeDatas);
384
385
        $segments = [];
386
        $segmentName = '';
387
        foreach ($routeDatas as $routeData) {
388
            foreach ($routeData as $item) {
389
                if (is_string($item)) {
390
                    // this segment is a static string
391
                    $segments[] = $item;
392
                    continue;
393
                }
394
395
                // This segment has a parameter: first element is the name
396
                if (!array_key_exists($item[0], $data)) {
397
                    // we don't have a data element for this segment: cancel
398
                    // testing this routeData item, so that we can try a less
399
                    // specific routeData item.
400
                    $segments = [];
401
                    $segmentName = $item[0];
402
                    break;
403
                }
404
                $segments[] = $data[$item[0]];
405
            }
406
            if (!empty($segments)) {
407
                // we found all the parameters for this route data, no need to check
408
                // less specific ones
409
                break;
410
            }
411
        }
412
413
        if (empty($segments)) {
414
            throw new InvalidArgumentException('Missing data for URL segment: ' . $segmentName);
415
        }
416
        $url = implode('', $segments);
417
418
        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...
419
            $url .= '?' . http_build_query($queryParams);
420
        }
421
422
        return $url;
423
    }
424
425
426
    /**
427
     * Build the path for a named route including the base path
428
     *
429
     * @param string $name        Route name
430
     * @param array  $data        Named argument replacement data
431
     * @param array  $queryParams Optional query string parameters
432
     *
433
     * @return string
434
     *
435
     * @throws RuntimeException         If named route does not exist
436
     * @throws InvalidArgumentException If required data not provided
437
     */
438
    public function pathFor($name, array $data = [], array $queryParams = [])
439
    {
440
        $url = $this->relativePathFor($name, $data, $queryParams);
441
442
        if ($this->basePath) {
443
            $url = $this->basePath . $url;
444
        }
445
446
        return $url;
447
    }
448
449
    /**
450
     * Build the path for a named route.
451
     *
452
     * This method is deprecated. Use pathFor() from now on.
453
     *
454
     * @param string $name        Route name
455
     * @param array  $data        Named argument replacement data
456
     * @param array  $queryParams Optional query string parameters
457
     *
458
     * @return string
459
     *
460
     * @throws RuntimeException         If named route does not exist
461
     * @throws InvalidArgumentException If required data not provided
462
     */
463
    public function urlFor($name, array $data = [], array $queryParams = [])
464
    {
465
        trigger_error('urlFor() is deprecated. Use pathFor() instead.', E_USER_DEPRECATED);
466
        return $this->pathFor($name, $data, $queryParams);
467
    }
468
}
469