Passed
Push — master ( fd8988...1427e9 )
by Mehmet
01:40
created

Dispatcher::createCachedRoute()   A

Complexity

Conditions 3
Paths 2

Size

Total Lines 10
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 12

Importance

Changes 0
Metric Value
dl 0
loc 10
ccs 0
cts 7
cp 0
rs 9.4285
c 0
b 0
f 0
cc 3
eloc 4
nc 2
nop 1
crap 12
1
<?php
2
declare(strict_types=1);
3
4
namespace Selami;
5
6
use FastRoute;
7
use RuntimeException;
8
9
class Dispatcher
10
{
11
12
    /**
13
     * Routes array to be registered.
14
     * Some routes may have aliases to be used in templating system
15
     * Route item can be defined using array key as an alias key.
16
     * Each route item is an array has items respectively: Request Method, Request Uri, Controller/Action, Return Type.
17
     *
18
     * @var array
19
     */
20
    private $routes;
21
22
23
    /**
24
     * Default return type if not noted in the $routes
25
     *
26
     * @var string
27
     */
28
    private $defaultReturnType;
29
30
    /**
31
     * @var null|string
32
     */
33
    private $cachedFile;
34
35
    /**
36
     * @var array
37
     */
38
    private $routerClosures = [];
39
40
41
    public function __construct(array $routes, int $defaultReturnType, ?string  $cachedFile)
42
    {
43
        $this->routes = $routes;
44
        $this->defaultReturnType = $defaultReturnType;
0 ignored issues
show
Documentation Bug introduced by
The property $defaultReturnType was declared of type string, but $defaultReturnType 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...
45
        $this->cachedFile = $cachedFile;
46
    }
47
48
    /**
49
     * Dispatch against the provided HTTP method verb and URI.
50
     *
51
     * @return FastRoute\Dispatcher
52
     * @throws RuntimeException;
53
     */
54
    public function dispatcher() : FastRoute\Dispatcher
55
    {
56
        $this->setRouteClosures();
57
        if ($this->cachedFile !== null && file_exists($this->cachedFile)) {
58
            return $this->cachedDispatcher();
59
        }
60
        /**
61
         * @var \FastRoute\RouteCollector $routeCollector
62
         */
63
        $routeCollector = new FastRoute\RouteCollector(
64
            new FastRoute\RouteParser\Std,
65
            new FastRoute\DataGenerator\GroupCountBased
66
        );
67
        $this->addRoutes($routeCollector);
68
        $this->createCachedRoute($routeCollector);
69
        return new FastRoute\Dispatcher\GroupCountBased($routeCollector->getData());
70
    }
71
72
    private function createCachedRoute($routeCollector) : void
73
    {
74
        if ($this->cachedFile !== null && !file_exists($this->cachedFile)) {
75
            /**
76
             * @var FastRoute\RouteCollector $routeCollector
77
             */
78
            $dispatchData = $routeCollector->getData();
79
            file_put_contents($this->cachedFile, '<?php return ' . var_export($dispatchData, true) . ';');
80
        }
81
    }
82
83
    /**
84
     * @return FastRoute\Dispatcher\GroupCountBased
85
     * @throws RuntimeException
86
     */
87
    private function cachedDispatcher() : FastRoute\Dispatcher\GroupCountBased
88
    {
89
        $dispatchData = include $this->cachedFile;
90
        if (!is_array($dispatchData)) {
91
            throw new RuntimeException('Invalid cache file "' . $this->cachedFile . '"');
92
        }
93
        return new FastRoute\Dispatcher\GroupCountBased($dispatchData);
94
    }
95
96
    /**
97
     * Define Closures for all routes that returns controller info to be used.
98
     *
99
     * @param FastRoute\RouteCollector $route
100
     */
101
    private function addRoutes(FastRoute\RouteCollector $route) : void
102
    {
103
        $routeIndex=0;
104
        foreach ($this->routes as $definedRoute) {
105
            $definedRoute[3] = $definedRoute[3] ?? $this->defaultReturnType;
106
            $routeName = 'routeClosure'.$routeIndex;
107
            $route->addRoute(strtoupper($definedRoute[0]), $definedRoute[1], $routeName);
108
            $routeIndex++;
109
        }
110
    }
111
112
    private function setRouteClosures() : void
113
    {
114
        $routeIndex=0;
115
        foreach ($this->routes as $definedRoute) {
116
            $definedRoute[3] = $definedRoute[3] ?? $this->defaultReturnType;
117
            $routeName = 'routeClosure'.$routeIndex;
118
            [$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...
119
            $returnType = ($returnType >=1 && $returnType <=7) ? $returnType : $this->defaultReturnType;
120
            $this->routerClosures[$routeName]= function ($args) use ($controller, $returnType) {
121
                return  ['controller' => $controller, 'returnType'=> $returnType, 'args'=> $args];
122
            };
123
            $routeIndex++;
124
        }
125
    }
126
127
128
129
    /**
130
     * Get route info for requested uri
131
     *
132
     * @param  array $routeInfo
133
     * @return array $routerData
134
     */
135
    public function runDispatcher(array $routeInfo) : array
136
    {
137
        $routeData = $this->getRouteData($routeInfo);
138
        $dispatchResults = [
139
            FastRoute\Dispatcher::METHOD_NOT_ALLOWED => [
140
                'status' => 405
141
            ],
142
            FastRoute\Dispatcher::FOUND => [
143
                'status'  => 200
144
            ],
145
            FastRoute\Dispatcher::NOT_FOUND => [
146
                'status' => 404
147
            ]
148
        ];
149
        return array_merge($routeData, $dispatchResults[$routeInfo[0]]);
150
    }
151
152
    /**
153
     * Get routeData according to dispatcher's results
154
     *
155
     * @param  array $routeInfo
156
     * @return array
157
     */
158
    private function getRouteData(array $routeInfo) : array
159
    {
160
        if ($routeInfo[0] === FastRoute\Dispatcher::FOUND) {
161
            [$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...
162
            return $this->routerClosures[$handler]($vars);
163
        }
164
        return [
165
            'status'        => 200,
166
            'returnType'    => Router::HTML,
167
            'definedRoute'  => null,
168
            'args'          => []
169
        ];
170
    }
171
}