Matcher::match()   A
last analyzed

Complexity

Conditions 4
Paths 4

Size

Total Lines 19
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Importance

Changes 4
Bugs 0 Features 0
Metric Value
eloc 10
c 4
b 0
f 0
dl 0
loc 19
rs 9.9332
cc 4
nc 4
nop 1
1
<?php
2
3
namespace DevPontes\Route\Traits;
4
5
use DevPontes\Route\Router;
6
7
trait Matcher
8
{
9
    /**
10
     * Set param
11
     *
12
     * @param string $routeUrl
13
     * @return array
14
     */
15
    protected function setParam(string $routeUrl): array
16
    {
17
        $param = null;
18
        $urlParts = explode('/', $routeUrl);
19
20
        foreach ($urlParts as $key => $part) {
21
            if (preg_match('/^\{.*\}$/', $part)) {
22
                $urlParts[$key] = $this->url[$key];
23
                $param = $this->url[$key];
24
            }
25
        }
26
27
        return [implode('/', $urlParts), $param];
28
    }
29
30
    /**
31
     * Find the corresponding route based on the given URL
32
     *
33
     * @param array $url
34
     * @return Router|null
35
     */
36
    protected function match(array $url): ?Router
37
    {
38
        $urlString = implode('/', $url);
39
40
        /** @var Router $route */
41
        foreach ($this->routes as $route) {
42
            if (count($url) !== count($route->getUrl(true))) {
43
                continue;
44
            }
45
46
            [$routeurl, $param] = $this->setParam($route->getUrl());
47
48
            if ($routeurl === $urlString) {
49
                $route->setParam($param);
50
                return $route;
51
            }
52
        }
53
54
        return null;
55
    }
56
}
57