Completed
Push — master ( d96b32...57aa95 )
by Sinnarasa
02:20
created

RoutesMatch   B

Complexity

Total Complexity 47

Size/Duplication

Total Lines 191
Duplicated Lines 3.14 %

Coupling/Cohesion

Components 1
Dependencies 3

Importance

Changes 10
Bugs 3 Features 2
Metric Value
wmc 47
c 10
b 3
f 2
lcom 1
cbo 3
dl 6
loc 191
rs 8.439

9 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 4 1
B match() 0 17 5
A paramMatch() 0 8 3
B routeMatch() 6 13 5
C generateTarget() 0 23 9
B validMethod() 0 7 7
A anonymous() 0 8 2
C mvc() 0 24 8
C template() 0 34 7

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 RoutesMatch 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 RoutesMatch, and based on these observations, apply Extract Interface, too.

1
<?php
2
3
namespace JetFire\Routing\Match;
4
5
6
use JetFire\Routing\Router;
7
8
/**
9
 * Class RoutesMatch
10
 * @package JetFire\Routing\Match
11
 */
12
class RoutesMatch implements MatcherInterface
13
{
14
15
    /**
16
     * @var
17
     */
18
    private $router;
19
    /**
20
     * @var array
21
     */
22
    private $request = [];
23
24
    /**
25
     * @param Router $router
26
     */
27
    public function __construct(Router $router)
28
    {
29
        $this->router = $router;
30
    }
31
32
    /**
33
     * @return bool
34
     */
35
    public function match()
36
    {
37
        $this->request = [];
38
        for ($i = 0; $i < $this->router->collection->countRoutes; ++$i) {
39
            $this->request['block'] = $this->router->collection->getRoutes('path_' . $i);
40
            $this->request['prefix'] = ($this->router->collection->getRoutes('prefix_' . $i) != '') ? $this->router->collection->getRoutes('prefix_' . $i) : '';
41
            foreach ($this->router->collection->getRoutes('routes_' . $i) as $route => $dependencies) {
42
                $this->request['path'] = $dependencies;
43
                $this->request['index'] = $i;
44
                $this->request['route'] = preg_replace_callback('#:([\w]+)#', [$this, 'paramMatch'], '/' . trim(trim($this->request['prefix'], '/') . '/' . trim($route, '/'), '/'));
45
                if ($this->routeMatch('#^' . $this->request['route'] . '$#'))
46
                    return $this->generateTarget();
47
            }
48
        }
49
        unset($this->request);
50
        return false;
51
    }
52
53
    /**
54
     * @param $match
55
     * @return string
56
     */
57
    private function paramMatch($match)
58
    {
59
        if (is_array($this->request['path']) && isset($this->request['path']['arguments'][$match[1]])) {
60
            $this->request['path']['arguments'][$match[1]] = str_replace('(', '(?:', $this->request['path']['arguments'][$match[1]]);
61
            return '(' . $this->request['path']['arguments'][$match[1]] . ')';
62
        }
63
        return '([^/]+)';
64
    }
65
66
    /**
67
     * @param $regex
68
     * @return bool
69
     */
70
    private function routeMatch($regex)
71
    {
72
        if (substr($this->request['route'], -1) == '*') {
73
            $pos = strpos($this->request['route'], '*');
74 View Code Duplication
            if (substr($this->router->route->getUrl(), 0, $pos) == substr($this->request['route'], 0, $pos))
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...
75
                if (isset($this->request)) return true;
76
        }
77 View Code Duplication
        if (preg_match($regex, $this->router->route->getUrl(), $this->request['parameters'])) {
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...
78
            array_shift($this->request['parameters']);
79
            return true;
80
        }
81
        return false;
82
    }
83
84
    /**
85
     * @return bool
86
     */
87
    private function generateTarget()
88
    {
89
        if(is_callable($this->request['path'])){
90
            $this->router->route->setCallback($this->request['path']);
91
            $this->router->route->setDetail($this->request);
92
            $this->anonymous();
93
            $this->router->route->setResponse(['code' => 202, 'message' => 'Accepted']);
94
        } else {
95
            if (isset($this->request['path']['name'])) $this->router->route->setName($this->request['path']['name']);
96
            if (isset($this->request['path']['method'])) $this->request['path']['method'] = is_array($this->request['path']['method']) ? $this->request['path']['method'] : [$this->request['path']['method']];
97
            if (isset($this->request['path']))
98
                (is_array($this->request['path']) && isset($this->request['path']['use']))
99
                    ? $this->router->route->setCallback($this->request['path']['use'])
100
                    : $this->router->route->setCallback($this->request['path']);
101
            $this->router->route->setDetail($this->request);
102
            if($this->validMethod()) {
103
                $this->anonymous();$this->mvc();$this->template();
104
                $this->router->route->setResponse(['code' => 202, 'message' => 'Accepted']);
105
            }else
106
                $this->router->route->setResponse(['code' => 405, 'message' => 'Method Not Allowed']);
107
        }
108
        return $this->router->route->hasTarget();
109
    }
110
111
    /**
112
     * @return bool
113
     */
114
    public function validMethod()
0 ignored issues
show
Coding Style introduced by
validMethod uses the super-global variable $_SERVER which is generally not recommended.

Instead of super-globals, we recommend to explicitly inject the dependencies of your class. This makes your code less dependent on global state and it becomes generally more testable:

// Bad
class Router
{
    public function generate($path)
    {
        return $_SERVER['HOST'].$path;
    }
}

// Better
class Router
{
    private $host;

    public function __construct($host)
    {
        $this->host = $host;
    }

    public function generate($path)
    {
        return $this->host.$path;
    }
}

class Controller
{
    public function myAction(Request $request)
    {
        // Instead of
        $page = isset($_GET['page']) ? intval($_GET['page']) : 1;

        // Better (assuming you use the Symfony2 request)
        $page = $request->query->get('page', 1);
    }
}
Loading history...
115
    {
116
        if (!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest')
117
            return (isset($this->request['path']['ajax']) && $this->request['path']['ajax'] === true) ? true : false;
118
        $method = (isset($this->router->route->getDetail()['path']['method'])) ? $this->router->route->getDetail()['path']['method'] : ['GET'];
119
        return (in_array($this->router->route->getMethod(), $method)) ? true : false;
120
    }
121
122
123
    /**
124
     * @return bool
125
     */
126
    public function anonymous()
127
    {
128
        if (is_callable($this->router->route->getCallback())) {
129
            $this->router->route->setTarget(['dispatcher' => 'JetFire\Routing\Dispatcher\FunctionDispatcher', 'closure' => $this->router->route->getCallback()]);
130
            return true;
131
        }
132
        return false;
133
    }
134
135
    /**
136
     * @return bool
137
     * @throws \Exception
138
     */
139
    public function mvc()
140
    {
141
        if (!$this->router->route->hasTarget() && strpos($this->router->route->getCallback(), '@') !== false) {
142
            $routes = explode('@', $this->router->route->getCallback());
143
            if (!isset($routes[1])) $routes[1] = 'index';
144
            $index = isset($this->request['index']) ? $this->request['index'] : 0;
145
            $class = (class_exists($routes[0]))
146
                ? $routes[0]
147
                : $this->router->collection->getRoutes()['namespace_'.$index].$routes[0];
148
            if (!class_exists($class))
149
                throw new \Exception('Class "' . $class . '." is not found');
150
            if (method_exists($class, $routes[1])) {
151
                $this->router->route->setTarget([
152
                    'dispatcher' => 'JetFire\Routing\Dispatcher\MvcDispatcher',
153
                    'di' => $this->router->getConfig()['di'],
154
                    'controller' => $class,
155
                    'action' => $routes[1]
156
                ]);
157
                return true;
158
            }
159
            throw new \Exception('The required method "' . $routes[1] . '" is not found in "' . $class . '"');
160
        }
161
        return false;
162
    }
163
164
    /**
165
     * @return bool
166
     * @throws \Exception
167
     */
168
    public function template()
169
    {
170
        if (!$this->router->route->hasTarget()) {
171
            $path = trim($this->router->route->getCallback(), '/');
172
            $extension = explode('.', $path);
173
            $extension = end($extension);
174
            $index = isset($this->request['index']) ? $this->request['index'] : 0;
175
            $block = $this->router->collection->getRoutes('path_'.$index);
176
            if (in_array('.' . $extension, $this->router->getConfig()['viewExtension'])) {
177
                if (is_file($block . $path)) {
178
                    $target = $block . $path;
179
                    $this->router->route->setTarget([
180
                        'dispatcher' => 'JetFire\Routing\Dispatcher\TemplateDispatcher',
181
                        'template' => $target,
182
                        'block' => $block,
183
                        'extension' => $extension,
184
                        'callback' => $this->router->getConfig()['viewCallback']
185
                    ]);
186
                    return true;
187
                }
188
                throw new \Exception('Template file "' . $path . '" is not found in "' . $block . '"');
189
            } else {
190
                foreach ($this->router->getConfig()['viewExtension'] as $ext) {
191
                    if (is_file($block . $path . $ext)){
192
                        $target = $block . $path . $ext;
193
                        $this->router->route->setTarget(['dispatcher' => 'JetFire\Routing\Dispatcher\TemplateDispatcher', 'template' => $target,'block' => $block,  'extension' => str_replace('.', '', $ext),'callback' => $this->router->getConfig()['viewCallback']]);
194
                        return true;
195
                    }
196
                }
197
                throw new \Exception('Template file "' . $path . '" is not found in "' .$block . '"');
198
            }
199
        }
200
        return false;
201
    }
202
}
203