Matcher::match()   A
last analyzed

Complexity

Conditions 3
Paths 3

Size

Total Lines 11
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 6
CRAP Score 3

Importance

Changes 0
Metric Value
dl 0
loc 11
ccs 6
cts 6
cp 1
rs 9.4285
c 0
b 0
f 0
cc 3
eloc 6
nc 3
nop 2
crap 3
1
<?php
2
declare(strict_types = 1);
3
4
namespace PTS\Routing;
5
6
class Matcher
7
{
8
    /** @var RouteService */
9
    protected $routeService;
10
    /** @var Route */
11
    protected $routeNotFound;
12
13 6
    public function __construct(RouteService $routeService)
14
    {
15 6
        $this->routeService = $routeService;
16 6
        $this->routeNotFound = new Route('', function () {
17 1
            return null;
18 6
        });
19 6
    }
20
21 1
    public function setNotFoundHandler(Route $route): self
22
    {
23 1
        $this->routeNotFound = $route;
24 1
        return $this;
25
    }
26
27 5
    public function match(CollectionRoute $routes, string $path): \Generator
28
    {
29 5
        foreach ($routes->getRoutes() as $route) {
30 4
            $activeRoute = $this->matchRule($route, $path);
31 4
            if ($activeRoute !== null) {
32 4
                yield $activeRoute;
33
            }
34
        }
35
36 2
        return yield $this->routeNotFound;
37
    }
38
39 4
    protected function matchRule(Route $route, string $pathUrl): ?Route
40
    {
41 4
        $activeRoute = null;
42
43 4
        $regexp = $this->routeService->makeRegExp($route);
44
45 4
        if (preg_match('~^'.$regexp.'$~Uiu', $pathUrl, $values)) {
46 3
            $filterValues = array_filter(array_keys($values), '\is_string');
47 3
            $matches = array_intersect_key($values, array_flip($filterValues));
48 3
            $activeRoute = $route->setMatches($matches);
49
        }
50
51 4
        return $activeRoute;
52
    }
53
}
54