ArrayMatcher::addResolver()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 4
rs 10
c 0
b 0
f 0
cc 1
eloc 2
nc 1
nop 1
1
<?php
2
3
namespace JetFire\Routing\Matcher;
4
5
use JetFire\Routing\Dispatcher\ClosureDispatcher;
6
use JetFire\Routing\Dispatcher\ControllerDispatcher;
7
use JetFire\Routing\Dispatcher\TemplateDispatcher;
8
use JetFire\Routing\Router;
9
10
/**
11
 * Class RoutesMatch
12
 * @package JetFire\Routing\Match
13
 */
14
class ArrayMatcher implements MatcherInterface
15
{
16
17
    /**
18
     * @var
19
     */
20
    private $router;
21
22
    /**
23
     * @var array
24
     */
25
    private $request = [];
26
27
    /**
28
     * @var array
29
     */
30
    private $resolver = ['isClosureAndTemplate', 'isControllerAndTemplate', 'isTemplate'];
31
32
    /**
33
     * @var array
34
     */
35
    private $dispatcher = [
36
        'isClosure' => ClosureDispatcher::class,
37
        'isController' => ControllerDispatcher::class,
38
        'isTemplate' => TemplateDispatcher::class,
39
        'isControllerAndTemplate' => [ControllerDispatcher::class, TemplateDispatcher::class],
40
        'isClosureAndTemplate' => [ClosureDispatcher::class, TemplateDispatcher::class],
41
    ];
42
43
    /**
44
     * @param Router $router
45
     */
46
    public function __construct(Router $router)
47
    {
48
        $this->router = $router;
49
    }
50
51
    /**
52
     * @param array $resolver
53
     */
54
    public function setResolver($resolver = [])
55
    {
56
        $this->resolver = $resolver;
57
    }
58
59
    /**
60
     * @param string $resolver
61
     */
62
    public function addResolver($resolver)
63
    {
64
        $this->resolver[] = $resolver;
65
    }
66
67
    /**
68
     * @return array
69
     */
70
    public function getResolver()
71
    {
72
        return $this->resolver;
73
    }
74
75
    /**
76
     * @param array $dispatcher
77
     */
78
    public function setDispatcher($dispatcher = [])
79
    {
80
        $this->dispatcher = $dispatcher;
81
    }
82
83
    /**
84
     * @param $method
85
     * @param $class
86
     * @internal param array $dispatcher
87
     */
88
    public function addDispatcher($method, $class)
89
    {
90
        $this->dispatcher[$method] = $class;
91
    }
92
93
    /**
94
     * @return bool
95
     */
96
    public function match()
97
    {
98
        $this->request = [];
99
        for ($i = 0; $i < $this->router->collection->countRoutes; ++$i) {
100
            $this->request['prefix'] = ($this->router->collection->getRoutes('prefix_' . $i) != '') ? $this->router->collection->getRoutes('prefix_' . $i) : '';
101
            $this->request['subdomain'] = ($this->router->collection->getRoutes('subdomain_' . $i) != '') ? $this->router->collection->getRoutes('subdomain_' . $i) : '';
102
            foreach ($this->router->collection->getRoutes('routes_' . $i) as $route => $params) {
103
                $this->request['params'] = $params;
104
                $this->request['collection_index'] = $i;
105
                if ($this->checkSubdomain($route)) {
106
                    $route = strstr($route, '/');
107
                    $this->request['route'] = preg_replace_callback('#:([\w]+)#', [$this, 'paramMatch'], '/' . trim(trim($this->request['prefix'], '/') . '/' . trim($route, '/'), '/'));
108
                    if ($this->routeMatch('#^' . $this->request['route'] . '$#')) {
109
                        $this->setCallback();
110
                        return $this->generateTarget();
111
                    }
112
                }
113
            }
114
        }
115
        return false;
116
    }
117
118
    /**
119
     * @param $route
120
     * @return bool
121
     */
122
    private function checkSubdomain($route)
0 ignored issues
show
Coding Style introduced by
checkSubdomain 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...
123
    {
124
        $url = (isset($_SERVER['REQUEST_SCHEME']) ? $_SERVER['REQUEST_SCHEME'] : 'http') . '://' . ($host = (isset($_SERVER['SERVER_NAME']) ? $_SERVER['SERVER_NAME'] : $_SERVER['HTTP_HOST']));
125
        $host = explode(':', $host)[0];
126
        $domain = $this->router->collection->getDomain($url);
127
        if (!empty($this->request['subdomain']) && $route[0] == '/') $route = trim($this->request['subdomain'], '.') . '.' . $domain . $route;
128
        if ($route[0] == '/') {
129
            return ($host != $domain) ? false : true;
130
        } elseif ($route[0] != '/' && $host != $domain) {
131
            $route = substr($route, 0, strpos($route, "/"));
132
            $route = str_replace('{host}', $domain, $route);
133
            $route = preg_replace_callback('#{subdomain}#', [$this, 'subdomainMatch'], $route);
134
            if (preg_match('#^' . $route . '$#', $host, $this->request['called_subdomain'])) {
135
                $this->request['called_subdomain'] = array_shift($this->request['called_subdomain']);
136
                $this->request['subdomain'] = str_replace('.' . $domain, '', $host);
137
                return true;
138
            }
139
        }
140
        return false;
141
    }
142
143
    /**
144
     * @return string
145
     */
146
    private function subdomainMatch()
147
    {
148
        if (is_array($this->request['params']) && isset($this->request['params']['subdomain'])) {
149
            return '(' . $this->request['params']['subdomain'] . ')';
150
        }
151
        return '([^/]+)';
152
    }
153
154
    /**
155
     * @param $match
156
     * @return string
157
     */
158
    private function paramMatch($match)
159
    {
160
        if (is_array($this->request['params']) && isset($this->request['params']['arguments'][$match[1]])) {
161
            $this->request['params']['arguments'][$match[1]] = str_replace('(', '(?:', $this->request['params']['arguments'][$match[1]]);
162
            return '(' . $this->request['params']['arguments'][$match[1]] . ')';
163
        }
164
        if(isset($this->router->collection->getRoutes('params_' . $this->request['collection_index'])['arguments'][$match[1]])){
165
            $this->request['params']['arguments'][$match[1]] = str_replace('(', '(?:', $this->router->collection->getRoutes('params_' . $this->request['collection_index'])['arguments'][$match[1]]);
166
            return '(' . $this->request['params']['arguments'][$match[1]] . ')';
167
        }
168
        return '([^/]+)';
169
    }
170
171
    /**
172
     * @param $regex
173
     * @return bool
174
     */
175
    private function routeMatch($regex)
176
    {
177
        $regex = (substr($this->request['route'], -1) == '*') ? '#^' . $this->request['route'] . '#' : $regex;
178
        if (preg_match($regex, $this->router->route->getUrl(), $this->request['parameters'])) {
179
            array_shift($this->request['parameters']);
180
            return true;
181
        }
182
        return false;
183
    }
184
185
    /**
186
     * @return bool
187
     */
188
    private function generateTarget()
189
    {
190
        if ($this->validMethod()) {
191
            foreach ($this->resolver as $resolver) {
192
                if (is_array($target = call_user_func_array([$this, $resolver], [$this->router->route->getCallback()]))) {
193
                    $this->setTarget($target);
194
                    return true;
195
                }
196
            }
197
        }
198
        $this->router->response->setStatusCode(405);
199
        return false;
200
    }
201
202
    /**
203
     * @param array $target
204
     */
205
    public function setTarget($target = [])
206
    {
207
        $index = isset($this->request['collection_index']) ? $this->request['collection_index'] : 0;
208
        $this->checkRequest('subdomain');
209
        $this->checkRequest('prefix');
210
        $this->router->route->setDetail($this->request);
211
        $this->router->route->setTarget($target);
212
        $this->router->route->addTarget('block', $this->router->collection->getRoutes('block_' . $index));
213
        $this->router->route->addTarget('view_dir', $this->router->collection->getRoutes('view_dir_' . $index));
214
        $this->router->route->addTarget('params', $this->router->collection->getRoutes('params_' . $index));
215
    }
216
217
    /**
218
     * @param $key
219
     */
220
    private function checkRequest($key)
221
    {
222
        if (strpos($this->request[$key], ':') !== false && isset($this->request['parameters'][0])) {
223
            $replacements = $this->request['parameters'];
224
            $keys = [];
225
            $this->request['@' . $key] = $this->request[$key];
226
            $this->request[$key] = preg_replace_callback('#:([\w?]+)#', function ($matches) use (&$replacements, &$keys) {
227
                $route_key = preg_replace("/[^A-Za-z0-9\\-_:]/", '', $matches[0]);
228
                $keys[$route_key] = isset($replacements[0]) ? $replacements[0] : null;
229
                return is_null($keys[$route_key]) ? '' : array_shift($replacements);
230
            }, $this->request[$key]);
231
            $this->request['keys'] = $keys;
232
            $this->request['parameters'] = $replacements;
233
        }
234
    }
235
236
    /**
237
     *
238
     */
239
    private function setCallback()
240
    {
241
        if (isset($this->request['params'])) {
242
            if (is_callable($this->request['params'])) {
243
                $this->router->route->setCallback($this->request['params']);
244
            } else {
245
                if (is_array($this->request['params']) && isset($this->request['params']['use'])) {
246
                    if (is_array($this->request['params']['use']) && isset($this->request['params']['use'][$this->router->route->getMethod()])) {
247
                        $this->router->route->setCallback($this->request['params']['use'][$this->router->route->getMethod()]);
248
                    } elseif (!is_array($this->request['params']['use'])) {
249
                        $this->router->route->setCallback($this->request['params']['use']);
250
                    }
251
                } else {
252
                    $this->router->route->setCallback($this->request['params']);
253
                }
254
                if (isset($this->request['params']['name'])) {
255
                    $this->router->route->setName($this->request['params']['name']);
256
                }
257
                if (isset($this->request['params']['method'])) {
258
                    $this->request['params']['method'] = is_array($this->request['params']['method']) ? $this->request['params']['method'] : [$this->request['params']['method']];
259
                }
260
            }
261
        }
262
    }
263
264
    /**
265
     * @return bool
266
     */
267
    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...
268
    {
269
        if (is_callable($this->request['params'])) {
270
            return true;
271
        }
272
        if (!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {
273
            return (isset($this->request['params']['ajax']) && $this->request['params']['ajax'] === true) ? true : false;
274
        }
275
        $method = (isset($this->request['params']['method'])) ? $this->request['params']['method'] : ['GET'];
276
        return (in_array($this->router->route->getMethod(), $method)) ? true : false;
277
    }
278
279
    /**
280
     * @param $callback
281
     * @return array|bool
282
     * @throws \Exception
283
     */
284 View Code Duplication
    public function isClosureAndTemplate($callback)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in 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...
285
    {
286
        if (is_array($cls = $this->isClosure($callback))) {
287
            if (is_array($this->request['params']) && isset($this->request['params']['template']) && is_array($tpl = $this->isTemplate($this->request['params']['template']))) {
288
                return array_merge(array_merge($cls, $tpl), [
289
                    'dispatcher' => $this->dispatcher['isClosureAndTemplate']
290
                ]);
291
            }
292
            return $cls;
293
        }
294
        return false;
295
    }
296
297
    /**
298
     * @param $callback
299
     * @return array|bool
300
     * @throws \Exception
301
     */
302 View Code Duplication
    public function isControllerAndTemplate($callback)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in 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...
303
    {
304
        if (is_array($ctrl = $this->isController($callback))) {
305
            if (is_array($this->request['params']) && isset($this->request['params']['template']) && is_array($tpl = $this->isTemplate($this->request['params']['template']))) {
306
                return array_merge(array_merge($ctrl, $tpl), [
307
                    'dispatcher' => $this->dispatcher['isControllerAndTemplate']
308
                ]);
309
            }
310
            return $ctrl;
311
        }
312
        return false;
313
    }
314
315
316
    /**
317
     * @param $callback
318
     * @return bool|array
319
     */
320
    public function isClosure($callback)
321
    {
322
        if (is_callable($callback)) {
323
            return [
324
                'dispatcher' => $this->dispatcher['isClosure'],
325
                'closure' => $callback
326
            ];
327
        }
328
        return false;
329
    }
330
331
    /**
332
     * @param $callback
333
     * @throws \Exception
334
     * @return bool|array
335
     */
336
    public function isController($callback)
337
    {
338
        if (is_string($callback) && strpos($callback, '@') !== false) {
339
            $routes = explode('@', $callback);
340
            if (!isset($routes[1])) $routes[1] = 'index';
341
            if ($routes[1] == '{method}') {
342
                $params = explode('/', trim(preg_replace('#' . rtrim(str_replace('*', '', $this->request['route']), '/') . '#', '', $this->router->route->getUrl()), '/'));
343
                $routes[1] = empty($params[0]) ? 'index' : $params[0];
344
                $this->request['@method'] = $routes[1];
345
                array_shift($params);
346
                $this->request['parameters'] = array_merge($this->request['parameters'], $params);
347
                if (preg_match('/[A-Z]/', $routes[1])) return false;
348
                $routes[1] = lcfirst(str_replace(' ', '', ucwords(str_replace('-', ' ', $routes[1]))));
349
            }
350
            $index = isset($this->request['collection_index']) ? $this->request['collection_index'] : 0;
351
            $class = (class_exists($routes[0]))
352
                ? $routes[0]
353
                : $this->router->collection->getRoutes()['ctrl_namespace_' . $index] . $routes[0];
354
            if (method_exists($class, $routes[1])) {
355
                return [
356
                    'dispatcher' => $this->dispatcher['isController'],
357
                    'di' => $this->router->getConfig()['di'],
358
                    'controller' => $class,
359
                    'action' => $routes[1]
360
                ];
361
            }
362
            if (!strpos($callback, '{method}') !== false) {
363
                throw new \Exception('The required method "' . $routes[1] . '" is not found in "' . $class . '"');
364
            }
365
        }
366
        return false;
367
    }
368
369
    /**
370
     * @param $callback
371
     * @throws \Exception
372
     * @return bool|array
373
     */
374
    public function isTemplate($callback)
375
    {
376
        if (is_string($callback) && strpos($callback, '@') === false) {
377
            $replace = isset($this->request['@method']) ? str_replace('-', '_', $this->request['@method']) : 'index';
378
            $path = str_replace('{template}', $replace, trim($callback, '/'));
379
            $extension = substr(strrchr($path, "."), 1);
380
            $index = isset($this->request['collection_index']) ? $this->request['collection_index'] : 0;
381
            $viewDir = is_array($viewDir = $this->router->collection->getRoutes('view_dir_' . $index)) ? $viewDir : [$viewDir];
382
            $target = null;
383
            if (in_array('.' . $extension, $this->router->getConfig()['templateExtension'])){
384
                foreach ($viewDir as $dir) {
385
                    if (is_file($fullPath = rtrim($dir, '/') . '/' . $path) || is_file($fullPath = $path)) $target = $fullPath;
386
                }
387
            }
388
            if(is_null($target)){
389
                foreach ($viewDir as $dir) {
390
                    foreach ($this->router->getConfig()['templateExtension'] as $ext) {
391
                        if (is_file($fullPath = rtrim($dir, '/') . '/' . $path . $ext) || is_file($fullPath = $path . $ext)) {
392
                            $target = $fullPath;
393
                            $extension = substr(strrchr($ext, "."), 1);
394
                            break;
395
                        }
396
                    }
397
                }
398
            }
399
            return [
400
                'dispatcher' => $this->dispatcher['isTemplate'],
401
                'template' => $target,
402
                'extension' => $extension,
403
                'callback' => $this->router->getConfig()['templateCallback']
404
            ];
405
        }
406
        return false;
407
    }
408
409
}
410