Passed
Branch master (701f59)
by Alexpts
02:08
created

Matcher::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 7
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 5
CRAP Score 1

Importance

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