Passed
Push — master ( c70469...a98a47 )
by Mehmet
03:46
created

Router::extractFolder()   A

Complexity

Conditions 3
Paths 4

Size

Total Lines 10
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 12

Importance

Changes 0
Metric Value
dl 0
loc 10
ccs 0
cts 10
cp 0
rs 9.4285
c 0
b 0
f 0
cc 3
eloc 6
nc 4
nop 2
crap 12
1
<?php
2
/**
3
 * Selami Router
4
 * PHP version 7.1+
5
 *
6
 * @category Library
7
 * @package  Router
8
 * @author   Mehmet Korkmaz <[email protected]>
9
 * @license  https://github.com/selamiphp/router/blob/master/LICENSE (MIT License)
10
 * @link     https://github.com/selamiphp/router
11
 */
12
13
declare(strict_types = 1);
14
15
namespace Selami;
16
17
use FastRoute;
18
use InvalidArgumentException;
19
use UnexpectedValueException;
20
21
/**
22
 * Router
23
 *
24
 * This class is responsible for registering route objects,
25
 * determining aliases if available and finding requested route
26
 */
27
final class Router
28
{
29
    const HTML = 1;
30
    const JSON = 2;
31
    const TEXT = 3;
32
    const XML = 4;
33
    const REDIRECT = 5;
34
    const DOWNLOAD = 6;
35
    const CUSTOM = 7;
36
37
    const OPTIONS = 'OPTIONS';
38
    const HEAD = 'HEAD';
39
    const GET = 'GET';
40
    const POST = 'POST';
41
    const PUT = 'PUT';
42
    const DELETE = 'DELETE';
43
    const PATCH = 'PATCH';
44
45
    /**
46
     * Routes array to be registered.
47
     * Some routes may have aliases to be used in templating system
48
     * Route item can be defined using array key as an alias key.
49
     * Each route item is an array has items respectively: Request Method, Request Uri, Controller/Action, Return Type.
50
     *
51
     * @var array
52
     */
53
    private $routes = [];
54
55
    /**
56
     * Aliases array to be registered.
57
     *
58
     * @var array
59
     */
60
    private $aliases = [];
61
62
    /**
63
     * HTTP request Method
64
     *
65
     * @var string
66
     */
67
    private $method;
68
69
    /**
70
     * Request Uri
71
     *
72
     * @var string
73
     */
74
    private $requestedPath;
75
76
    /**
77
     * Default return type if not noted in the $routes
78
     *
79
     * @var string
80
     */
81
    private $defaultReturnType;
82
83
    /**
84
     * @var null|string
85
     */
86
    private $cachedFile;
87
88
    /**
89
     * @var array
90
     */
91
    private $routerClosures = [];
92
93
    /**
94
     * Valid Request Methods array.
95
     * Make sures about requested methods.
96
     *
97
     * @var array
98
     */
99
    private static $validRequestMethods = [
100
        'GET',
101
        'OPTIONS',
102
        'HEAD',
103
        'POST',
104
        'PUT',
105
        'DELETE',
106
        'PATCH'
107
    ];
108
109
    /**
110
     * Router constructor.
111
     * Create new router.
112
     *
113
     * @param  int    $defaultReturnType
114
     * @param  string $method
115
     * @param  string $requestedPath
116
     * @param  string $folder
117
     * @param  string $cachedFile
118
     * @throws UnexpectedValueException
119
     */
120
    public function __construct(
121
        int $defaultReturnType,
122
        string $method,
123
        string $requestedPath,
124
        string $folder = '',
125
        ?string $cachedFile = null
126
    ) {
127
        if (!in_array($method, self::$validRequestMethods, true)) {
128
            $message = sprintf('%s is not valid Http request method.', $method);
129
            throw new UnexpectedValueException($message);
130
        }
131
        $this->method = $method;
132
        $this->requestedPath = $this->extractFolder($requestedPath, $folder);
133
        $this->defaultReturnType = ($defaultReturnType >=1 && $defaultReturnType <=7) ? $defaultReturnType : self::HTML;
0 ignored issues
show
Documentation Bug introduced by
The property $defaultReturnType was declared of type string, but $defaultReturnType >= 1 ...ReturnType : self::HTML is of type integer. Maybe add a type cast?

This check looks for assignments to scalar types that may be of the wrong type.

To ensure the code behaves as expected, it may be a good idea to add an explicit type cast.

$answer = 42;

$correct = false;

$correct = (bool) $answer;
Loading history...
134
        $this->cachedFile = $cachedFile;
135
    }
136
137
    /**
138
     * Remove sub folder from requestedPath if defined
139
     *
140
     * @param  string $requestPath
141
     * @param  string $folder
142
     * @return string
143
     */
144
    private function extractFolder(string $requestPath, string $folder) : string
145
    {
146
        if (!empty($folder)) {
147
            $requestPath = '/' . trim(preg_replace('#^/' . $folder . '#msi', '/', $requestPath), '/');
148
        }
149
        if ($requestPath === '') {
150
            $requestPath = '/';
151
        }
152
        return $requestPath;
153
    }
154
155
    /**
156
     * Add route to routes list
157
     *
158
     * @param  string|array requestMethods
159
     * @param  string                      $route
160
     * @param  string                      $action
161
     * @param  int                         $returnType
162
     * @param  string                      $alias
163
     * @throws InvalidArgumentException
164
     * @throws UnexpectedValueException
165
     */
166
    public function add(
167
        $requestMethods,
168
        string $route,
169
        string $action,
170
        ?int $returnType = null,
171
        ?string $alias = null
172
    ) : void {
173
    
174
        $requestMethodsGiven = is_array($requestMethods) ? (array) $requestMethods : [0 => $requestMethods];
175
        $returnType = $this->determineReturnType($returnType);
176
        foreach ($requestMethodsGiven as $requestMethod) {
177
            $this->checkRequestMethodParameterType($requestMethod);
178
            $this->checkRequestMethodIsValid($requestMethod);
179
            if ($alias !== null) {
180
                $this->aliases[$alias] = $route;
181
            }
182
            $this->routes[] = [strtoupper($requestMethod), $route, $action, $returnType];
183
        }
184
    }
185
186
    /**
187
     * @param string $method
188
     * @param array  $args
189
     * @throws UnexpectedValueException
190
     * @throws InvalidArgumentException
191
     */
192
    public function __call(string $method, array $args) : void
193
    {
194
        $this->checkRequestMethodIsValid($method);
195
        $defaults = [
196
            null,
197
            null,
198
            $this->defaultReturnType,
199
            null
200
        ];
201
        [$route, $action, $returnType, $alias] = array_merge($args, $defaults);
4 ignored issues
show
Bug introduced by
The variable $route does not exist. Did you forget to declare it?

This check marks access to variables or properties that have not been declared yet. While PHP has no explicit notion of declaring a variable, accessing it before a value is assigned to it is most likely a bug.

Loading history...
Bug introduced by
The variable $action does not exist. Did you forget to declare it?

This check marks access to variables or properties that have not been declared yet. While PHP has no explicit notion of declaring a variable, accessing it before a value is assigned to it is most likely a bug.

Loading history...
Bug introduced by
The variable $returnType does not exist. Did you forget to declare it?

This check marks access to variables or properties that have not been declared yet. While PHP has no explicit notion of declaring a variable, accessing it before a value is assigned to it is most likely a bug.

Loading history...
Bug introduced by
The variable $alias does not exist. Did you forget to declare it?

This check marks access to variables or properties that have not been declared yet. While PHP has no explicit notion of declaring a variable, accessing it before a value is assigned to it is most likely a bug.

Loading history...
202
        $this->add($method, $route, $action, $returnType, $alias);
203
    }
204
205
    /**
206
     * @param int|null $returnType
207
     * @return int
208
     */
209
    private function determineReturnType(?int $returnType) : int
210
    {
211
        if ($returnType === null) {
212
            return $this->defaultReturnType;
213
        }
214
        return ($returnType >=1 && $returnType <=7) ? $returnType : self::HTML;
215
    }
216
217
    /**
218
     * @param string $requestMethod
219
     * Checks if request method is valid
220
     * @throws UnexpectedValueException;
221
     */
222
    private function checkRequestMethodIsValid(string $requestMethod) : void
223
    {
224
        if (!in_array(strtoupper($requestMethod), self::$validRequestMethods, true)) {
225
            $message = sprintf('%s is not valid Http request method.', $requestMethod);
226
            throw new UnexpectedValueException($message);
227
        }
228
    }
229
230
    /**
231
     * @param $requestMethod
232
     * @throws InvalidArgumentException
233
     */
234
    private function checkRequestMethodParameterType($requestMethod) : void
235
    {
236
        $requestMethodParameterType = gettype($requestMethod);
237
        if (!in_array($requestMethodParameterType, ['array', 'string'], true)) {
238
            $message = sprintf(
239
                'Request method must be string or array but %s given.',
240
                $requestMethodParameterType
241
            );
242
            throw new InvalidArgumentException($message);
243
        }
244
    }
245
246
    /**
247
     * Dispatch against the provided HTTP method verb and URI.
248
     *
249
     * @return FastRoute\Dispatcher
250
     */
251
    private function dispatcher() : FastRoute\Dispatcher
252
    {
253
254
        $this->setRouteClosures();
255
        if ($this->cachedFile !== null) {
256
            return $this->cachedDispatcher();
257
        }
258
        return $this->simpleDispatcher();
259
    }
260
261
    private function simpleDispatcher() : FastRoute\Dispatcher\GroupCountBased
262
    {
263
        $options = [
264
            'routeParser' => FastRoute\RouteParser\Std::class,
265
            'dataGenerator' => FastRoute\DataGenerator\GroupCountBased::class,
266
            'dispatcher' => FastRoute\Dispatcher\GroupCountBased::class,
267
            'routeCollector' => FastRoute\RouteCollector::class,
268
        ];
269
        /**
270
        * @var \FastRoute\RouteCollector $routeCollector
271
        */
272
        $routeCollector = new $options['routeCollector'](
273
            new $options['routeParser'], new $options['dataGenerator']
274
        );
275
        $this->addRoutes($routeCollector);
276
277
        return new $options['dispatcher']($routeCollector->getData());
278
    }
279
280
    private function cachedDispatcher() : FastRoute\Dispatcher\GroupCountBased
281
    {
282
        $options = [
283
            'routeParser' => FastRoute\RouteParser\Std::class,
284
            'dataGenerator' => FastRoute\DataGenerator\GroupCountBased::class,
285
            'dispatcher' => FastRoute\Dispatcher\GroupCountBased::class,
286
            'routeCollector' => FastRoute\RouteCollector::class
287
        ];
288
        if (file_exists($this->cachedFile)) {
289
            $dispatchData = include $this->cachedFile;
290
            if (!is_array($dispatchData)) {
291
                throw new \RuntimeException('Invalid cache file "' . $options['cacheFile'] . '"');
292
            }
293
            return new $options['dispatcher']($dispatchData);
294
        }
295
        $routeCollector = new $options['routeCollector'](
296
            new $options['routeParser'], new $options['dataGenerator']
297
        );
298
        $this->addRoutes($routeCollector);
299
        /**
300
        * @var FastRoute\RouteCollector $routeCollector
301
        */
302
        $dispatchData = $routeCollector->getData();
303
        file_put_contents(
304
            $this->cachedFile,
305
            '<?php return ' . var_export($dispatchData, true) . ';'
306
        );
307
        return new $options['dispatcher']($dispatchData );
308
    }
309
310
    /**
311
     * Define Closures for all routes that returns controller info to be used.
312
     *
313
     * @param FastRoute\RouteCollector $route
314
     */
315
    private function addRoutes(FastRoute\RouteCollector $route) : void
316
    {
317
        $routeIndex=0;
318
        foreach ($this->routes as $definedRoute) {
319
            $definedRoute[3] = $definedRoute[3] ?? $this->defaultReturnType;
320
            $routeName = 'routeClosure'.$routeIndex;
321
            $route->addRoute(strtoupper($definedRoute[0]), $definedRoute[1], $routeName);
322
            $routeIndex++;
323
        }
324
    }
325
    private function setRouteClosures() : void
326
    {
327
        $routeIndex=0;
328
        foreach ($this->routes as $definedRoute) {
329
            $definedRoute[3] = $definedRoute[3] ?? $this->defaultReturnType;
330
            $routeName = 'routeClosure'.$routeIndex;
331
            [$requestMedhod, $url, $controller, $returnType] = $definedRoute;
4 ignored issues
show
Bug introduced by
The variable $requestMedhod does not exist. Did you forget to declare it?

This check marks access to variables or properties that have not been declared yet. While PHP has no explicit notion of declaring a variable, accessing it before a value is assigned to it is most likely a bug.

Loading history...
Bug introduced by
The variable $url does not exist. Did you forget to declare it?

This check marks access to variables or properties that have not been declared yet. While PHP has no explicit notion of declaring a variable, accessing it before a value is assigned to it is most likely a bug.

Loading history...
Bug introduced by
The variable $controller does not exist. Did you forget to declare it?

This check marks access to variables or properties that have not been declared yet. While PHP has no explicit notion of declaring a variable, accessing it before a value is assigned to it is most likely a bug.

Loading history...
Bug introduced by
The variable $returnType 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...
332
            $returnType = ($returnType >=1 && $returnType <=7) ? $returnType : $this->defaultReturnType;
333
            $this->routerClosures[$routeName]= function ($args) use ($controller, $returnType) {
334
                return  ['controller' => $controller, 'returnType'=> $returnType, 'args'=> $args];
335
            };
336
            $routeIndex++;
337
        }
338
    }
339
340
    /**
341
     * Get router data that includes route info and aliases
342
     *
343
     * @return array
344
     */
345
    public function getRoute() : array
346
    {
347
        $dispatcher = $this->dispatcher();
348
        $routeInfo  = $dispatcher->dispatch($this->method, $this->requestedPath);
349
        $route = $this->runDispatcher($routeInfo);
350
        $routerData = [
351
            'route'     => $route,
352
            'aliases'   => $this->aliases
353
        ];
354
        return $routerData;
355
    }
356
357
    /**
358
     * Get route info for requested uri
359
     *
360
     * @param  array $routeInfo
361
     * @return array $routerData
362
     */
363
    private function runDispatcher(array $routeInfo) : array
364
    {
365
        $routeData = $this->getRouteData($routeInfo);
366
        $dispatchResults = [
367
            FastRoute\Dispatcher::METHOD_NOT_ALLOWED => [
368
                'status' => 405
369
            ],
370
            FastRoute\Dispatcher::FOUND => [
371
                'status'  => 200
372
            ],
373
            FastRoute\Dispatcher::NOT_FOUND => [
374
                'status' => 404
375
            ]
376
        ];
377
        return array_merge($routeData, $dispatchResults[$routeInfo[0]]);
378
    }
379
380
    /**
381
     * Get routeData according to dispatcher's results
382
     *
383
     * @param  array $routeInfo
384
     * @return array
385
     */
386
    private function getRouteData(array $routeInfo) : array
387
    {
388
        if ($routeInfo[0] === FastRoute\Dispatcher::FOUND) {
389
            [$dispatcher, $handler, $vars] = $routeInfo;
3 ignored issues
show
Bug introduced by
The variable $dispatcher does not exist. Did you forget to declare it?

This check marks access to variables or properties that have not been declared yet. While PHP has no explicit notion of declaring a variable, accessing it before a value is assigned to it is most likely a bug.

Loading history...
Bug introduced by
The variable $handler does not exist. Did you forget to declare it?

This check marks access to variables or properties that have not been declared yet. While PHP has no explicit notion of declaring a variable, accessing it before a value is assigned to it is most likely a bug.

Loading history...
Bug introduced by
The variable $vars does not exist. Did you forget to declare it?

This check marks access to variables or properties that have not been declared yet. While PHP has no explicit notion of declaring a variable, accessing it before a value is assigned to it is most likely a bug.

Loading history...
390
            return $this->routerClosures[$handler]($vars);
391
        }
392
        return [
393
            'status'        => 200,
394
            'returnType'    => Router::HTML,
395
            'definedRoute'  => null,
396
            'args'          => []
397
        ];
398
    }
399
}
400