Completed
Push — master ( 8801ad...e19554 )
by Alexpts
02:50
created

Matcher::match()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 11
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 12

Importance

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