Completed
Push — master ( 220ceb...ab9a78 )
by Sinnarasa
02:32
created

RoutesMatch::match()   B

Complexity

Conditions 5
Paths 7

Size

Total Lines 17
Code Lines 13

Duplication

Lines 0
Ratio 0 %

Importance

Changes 5
Bugs 0 Features 2
Metric Value
c 5
b 0
f 2
dl 0
loc 17
rs 8.8571
cc 5
eloc 13
nc 7
nop 0
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
     * @var array
26
     */
27
    private $matcher = ['matchClosure','matchController','matchTemplate'];
28
29
    /**
30
     * @param Router $router
31
     */
32
    public function __construct(Router $router)
33
    {
34
        $this->router = $router;
35
    }
36
37
    /**
38
     * @param string $matcher
39
     */
40
    public function addMatcher($matcher){
41
        $this->matcher[] = $matcher;
42
    }
43
44
    /**
45
     * @return array
46
     */
47
    public function getMatcher()
48
    {
49
        return $this->matcher;
50
    }
51
52
    /**
53
     * @return bool
54
     */
55
    public function match()
56
    {
57
        $this->request = [];
58
        for ($i = 0; $i < $this->router->collection->countRoutes; ++$i) {
59
            $this->request['block'] = $this->router->collection->getRoutes('path_' . $i);
60
            $this->request['prefix'] = ($this->router->collection->getRoutes('prefix_' . $i) != '') ? $this->router->collection->getRoutes('prefix_' . $i) : '';
61
            foreach ($this->router->collection->getRoutes('routes_' . $i) as $route => $dependencies) {
62
                $this->request['path'] = $dependencies;
63
                $this->request['index'] = $i;
64
                $this->request['route'] = preg_replace_callback('#:([\w]+)#', [$this, 'paramMatch'], '/' . trim(trim($this->request['prefix'], '/') . '/' . trim($route, '/'), '/'));
65
                if ($this->routeMatch('#^' . $this->request['route'] . '$#'))
66
                    return $this->generateTarget();
67
            }
68
        }
69
        unset($this->request);
70
        return false;
71
    }
72
73
    /**
74
     * @param $match
75
     * @return string
76
     */
77
    private function paramMatch($match)
78
    {
79
        if (is_array($this->request['path']) && isset($this->request['path']['arguments'][$match[1]])) {
80
            $this->request['path']['arguments'][$match[1]] = str_replace('(', '(?:', $this->request['path']['arguments'][$match[1]]);
81
            return '(' . $this->request['path']['arguments'][$match[1]] . ')';
82
        }
83
        return '([^/]+)';
84
    }
85
86
    /**
87
     * @param $regex
88
     * @return bool
89
     */
90
    private function routeMatch($regex)
91
    {
92
        if (substr($this->request['route'], -1) == '*') {
93
            $pos = strpos($this->request['route'], '*');
94 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...
95
                if (isset($this->request)) return true;
96
        }
97 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...
98
            array_shift($this->request['parameters']);
99
            return true;
100
        }
101
        return false;
102
    }
103
104
    /**
105
     * @return bool
106
     */
107
    private function generateTarget()
108
    {
109
        if(is_callable($this->request['path'])){
110
            $this->router->route->setCallback($this->request['path']);
111
            $this->router->route->setDetail($this->request);
112
            $this->matchClosure();
113
            $this->router->route->setResponse(['code' => 202, 'message' => 'Accepted']);
114
        } else {
115
            if (isset($this->request['path']['name'])) $this->router->route->setName($this->request['path']['name']);
116
            if (isset($this->request['path']['method'])) $this->request['path']['method'] = is_array($this->request['path']['method']) ? $this->request['path']['method'] : [$this->request['path']['method']];
117
            if (isset($this->request['path']))
118
                (is_array($this->request['path']) && isset($this->request['path']['use']))
119
                    ? $this->router->route->setCallback($this->request['path']['use'])
120
                    : $this->router->route->setCallback($this->request['path']);
121
            $this->router->route->setDetail($this->request);
122
            if($this->validMethod()) {
123
                foreach($this->matcher as $matcher)
124
                    call_user_func([$this,$matcher]);
125
                $this->router->route->setResponse(['code' => 202, 'message' => 'Accepted']);
126
            }else
127
                $this->router->route->setResponse(['code' => 405, 'message' => 'Method Not Allowed']);
128
        }
129
        return $this->router->route->hasTarget();
130
    }
131
132
    /**
133
     * @return bool
134
     */
135
    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...
136
    {
137
        if (!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest')
138
            return (isset($this->request['path']['ajax']) && $this->request['path']['ajax'] === true) ? true : false;
139
        $method = (isset($this->router->route->getDetail()['path']['method'])) ? $this->router->route->getDetail()['path']['method'] : ['GET'];
140
        return (in_array($this->router->route->getMethod(), $method)) ? true : false;
141
    }
142
143
144
    /**
145
     * @return bool
146
     */
147
    public function matchClosure()
148
    {
149
        if (is_callable($this->router->route->getCallback())) {
150
            $this->router->route->setTarget(['dispatcher' => 'JetFire\Routing\Dispatcher\ClosureDispatcher', 'closure' => $this->router->route->getCallback()]);
151
            return true;
152
        }
153
        return false;
154
    }
155
156
    /**
157
     * @return bool
158
     * @throws \Exception
159
     */
160
    public function matchController()
161
    {
162
        if (!$this->router->route->hasTarget() && strpos($this->router->route->getCallback(), '@') !== false) {
163
            $routes = explode('@', $this->router->route->getCallback());
164
            if (!isset($routes[1])) $routes[1] = 'index';
165
            $index = isset($this->request['index']) ? $this->request['index'] : 0;
166
            $class = (class_exists($routes[0]))
167
                ? $routes[0]
168
                : $this->router->collection->getRoutes()['namespace_'.$index].$routes[0];
169
            if (!class_exists($class))
170
                throw new \Exception('Class "' . $class . '." is not found');
171
            if (method_exists($class, $routes[1])) {
172
                $this->router->route->setTarget([
173
                    'dispatcher' => 'JetFire\Routing\Dispatcher\ControllerDispatcher',
174
                    'di' => $this->router->getConfig()['di'],
175
                    'controller' => $class,
176
                    'action' => $routes[1]
177
                ]);
178
                return true;
179
            }
180
            throw new \Exception('The required method "' . $routes[1] . '" is not found in "' . $class . '"');
181
        }
182
        return false;
183
    }
184
185
    /**
186
     * @return bool
187
     * @throws \Exception
188
     */
189
    public function matchTemplate()
190
    {
191
        if (!$this->router->route->hasTarget()) {
192
            $path = trim($this->router->route->getCallback(), '/');
193
            $extension = explode('.', $path);
194
            $extension = end($extension);
195
            $index = isset($this->request['index']) ? $this->request['index'] : 0;
196
            $block = $this->router->collection->getRoutes('path_'.$index);
197
            if (in_array('.' . $extension, $this->router->getConfig()['viewExtension'])) {
198
                if (is_file($block . $path)) {
199
                    $target = $block . $path;
200
                    $this->router->route->setTarget([
201
                        'dispatcher' => 'JetFire\Routing\Dispatcher\TemplateDispatcher',
202
                        'template' => $target,
203
                        'block' => $block,
204
                        'extension' => $extension,
205
                        'callback' => $this->router->getConfig()['viewCallback']
206
                    ]);
207
                    return true;
208
                }
209
                throw new \Exception('Template file "' . $path . '" is not found in "' . $block . '"');
210
            } else {
211
                foreach ($this->router->getConfig()['viewExtension'] as $ext) {
212
                    if (is_file($block . $path . $ext)){
213
                        $target = $block . $path . $ext;
214
                        $this->router->route->setTarget(['dispatcher' => 'JetFire\Routing\Dispatcher\TemplateDispatcher', 'template' => $target,'block' => $block,  'extension' => str_replace('.', '', $ext),'callback' => $this->router->getConfig()['viewCallback']]);
215
                        return true;
216
                    }
217
                }
218
                throw new \Exception('Template file "' . $path . '" is not found in "' .$block . '"');
219
            }
220
        }
221
        return false;
222
    }
223
}
224