Middleware   B
last analyzed

Complexity

Total Complexity 46

Size/Duplication

Total Lines 204
Duplicated Lines 4.9 %

Coupling/Cohesion

Components 2
Dependencies 2

Importance

Changes 4
Bugs 1 Features 0
Metric Value
wmc 46
lcom 2
cbo 2
dl 10
loc 204
rs 8.3999
c 4
b 1
f 0

12 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 4 1
A getMiddleware() 0 4 1
A setCallbackAction() 0 4 1
B setMiddleware() 0 13 5
A getCallbacks() 0 4 2
A globalMiddleware() 0 6 2
A blockMiddleware() 6 9 3
A classMiddleware() 0 10 4
A routeMiddleware() 4 9 4
B callHandlers() 0 8 5
C handle() 0 31 13
B getClass() 0 15 5

How to fix   Duplicated Code    Complexity   

Duplicated Code

Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.

Common duplication problems, and corresponding solutions are:

Complex Class

 Tip:   Before tackling complexity, make sure that you eliminate any duplication first. This often can reduce the size of classes significantly.

Complex classes like Middleware often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes. You can also have a look at the cohesion graph to spot any un-connected, or weakly-connected components.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

While breaking up the class, it is a good idea to analyze how other classes use Middleware, and based on these observations, apply Extract Interface, too.

1
<?php
2
3
namespace JetFire\Routing;
4
5
use ReflectionMethod;
6
7
8
/**
9
 * Class Middleware
10
 * @package JetFire\Routing
11
 */
12
class Middleware implements MiddlewareInterface
13
{
14
15
    /**
16
     * @var Router
17
     */
18
    private $router;
19
    /**
20
     * @var bool
21
     */
22
    private $next = true;
23
24
    /**
25
     * @var array
26
     */
27
    protected $callbacks = [
28
        'globalMiddleware',
29
        'blockMiddleware',
30
        'classMiddleware',
31
        'routeMiddleware',
32
    ];
33
34
    /**
35
     * @var array
36
     */
37
    private $middleware = [];
38
39
    /**
40
     * @param Router $router
41
     */
42
    public function __construct(Router $router)
43
    {
44
        $this->router = $router;
45
    }
46
47
    /**
48
     * @return array
49
     */
50
    public function getMiddleware()
51
    {
52
        return $this->middleware;
53
    }
54
55
    /**
56
     * @param $action
57
     * @param $middleware
58
     * @return mixed|void
59
     */
60
    public function setCallbackAction($action, $middleware)
61
    {
62
        $this->setMiddleware($action, $middleware);
63
    }
64
65
    /**
66
     * @param $action
67
     * @param $middleware
68
     */
69
    private function setMiddleware($action, $middleware)
70
    {
71
        if (is_string($middleware)) {
72
            $middleware = rtrim($middleware, '/');
73
        }
74
        if (is_array($middleware)) {
75
            $this->middleware[$action] = $middleware;
76
        } elseif (is_file($middleware) && is_array($mid = include $middleware)) {
77
            $this->middleware[$action] = $mid;
78
        } else {
79
            throw new \InvalidArgumentException('Accepted argument for setMiddleware are array and array file');
80
        }
81
    }
82
83
    /**
84
     * @param $action
85
     * @return Router
86
     */
87
    public function getCallbacks($action)
88
    {
89
        return $action == 'after' ? array_reverse($this->callbacks) : $this->callbacks;
90
    }
91
92
    /**
93
     * @description global middleware
94
     * @param $action
95
     */
96
    public function globalMiddleware($action)
97
    {
98
        if (isset($this->middleware[$action]['global_middleware'])) {
99
            $this->callHandlers($this->middleware[$action]['global_middleware']);
100
        }
101
    }
102
103
    /**
104
     * @description block middleware
105
     * @param $action
106
     */
107
    public function blockMiddleware($action)
108
    {
109 View Code Duplication
        if (isset($this->middleware[$action]['block_middleware'])) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
110
            if (isset($this->middleware[$action]['block_middleware'][$this->router->route->getTarget('block')])) {
111
                $blocks = $this->middleware[$action]['block_middleware'][$this->router->route->getTarget('block')];
112
                $this->callHandlers($blocks);
113
            }
114
        }
115
    }
116
117
    /**
118
     * @description controller middleware
119
     * @param $action
120
     */
121
    public function classMiddleware($action)
122
    {
123
        if (isset($this->middleware[$action]['class_middleware'])) {
124
            $ctrl = str_replace('\\', '/', $this->router->route->getTarget('controller'));
125
            if (isset($this->middleware[$action]['class_middleware'][$ctrl]) && class_exists($this->router->route->getTarget('controller'))) {
126
                $classes = $this->middleware[$action]['class_middleware'][$ctrl];
127
                $this->callHandlers($classes);
128
            }
129
        }
130
    }
131
132
    /**
133
     * @description route middleware
134
     * @param $action
135
     */
136
    public function routeMiddleware($action)
137
    {
138
        if (isset($this->middleware[$action]['route_middleware'])) {
139 View Code Duplication
            if (isset($this->router->route->getPath()['middleware']) && class_exists($this->middleware[$action]['route_middleware'][$this->router->route->getPath()['middleware']])) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
140
                $classes = $this->middleware[$action]['route_middleware'][$this->router->route->getPath()['middleware']];
141
                $this->callHandlers($classes);
142
            }
143
        }
144
    }
145
146
    /**
147
     * @param $handlers
148
     * @param array $params
149
     */
150
    private function callHandlers($handlers, $params = []){
151
        $handlers = is_array($handlers) ? $handlers : [$handlers];
152
        foreach ($handlers as $handler) {
153
            if($this->next && $this->handle($handler, $params) !== true){
154
                break;
155
            }
156
        }
157
    }
158
159
    /**
160
     * @param $callback
161
     * @param array $params
162
     * @return mixed
163
     */
164
    private function handle($callback, $params = [])
165
    {
166
        $callback = explode('@', $callback);
167
        $response = true;
168
        $method = isset($callback[1]) ? $callback[1] : 'handle';
169
        if (class_exists($callback[0])) {
170
            $instance = call_user_func($this->router->getConfig()['di'], $callback[0]);
171
            if (method_exists($instance, $method)) {
172
                $reflectionMethod = new ReflectionMethod($instance, $method);
173
                $dependencies = $params;
174
                foreach ($reflectionMethod->getParameters() as $arg) {
175
                    if (!is_null($arg->getClass())) {
176
                        $dependencies[] = $this->getClass($arg->getClass()->name);
177
                    }
178
                }
179
                $dependencies = array_merge($dependencies, [$this->router->route]);
180
                $response = $reflectionMethod->invokeArgs($instance, $dependencies);
181
                if(is_array($response) && isset($response['call'])){
182
                    if(isset($response['response']) && $response['response'] instanceof ResponseInterface){
183
                        $this->router->response = $response['response'];
184
                    }
185
                    $params = isset($response['params']) ? $response['params']: [];
186
                    $this->callHandlers($response['call'], $params);
187
                    $this->next = isset($response['next']) ? (bool)$response['next'] : false;
188
                } else if ($response instanceof ResponseInterface) {
189
                    $this->router->response = $response;
190
                }
191
            }
192
        }
193
        return $response;
194
    }
195
196
    /**
197
     * @param $class
198
     * @return Route|RouteCollection|Router|mixed
199
     */
200
    private function getClass($class)
201
    {
202
        switch ($class) {
203
            case Route::class:
204
                return $this->router->route;
205
            case Router::class:
206
                return $this->router;
207
            case RouteCollection::class:
208
                return $this->router->collection;
209
            case ResponseInterface::class:
210
                return $this->router->response;
211
            default:
212
                return call_user_func_array($this->router->getConfig()['di'], [$class]);
213
        }
214
    }
215
}
216