Completed
Push — master ( 528eb4...5ffde5 )
by n
01:41
created

Router::match()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 16
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 8
CRAP Score 3

Importance

Changes 0
Metric Value
dl 0
loc 16
ccs 8
cts 8
cp 1
rs 9.4285
c 0
b 0
f 0
cc 3
eloc 8
nc 3
nop 1
crap 3
1
<?php
2
declare(strict_types=1);
3
4
namespace N1215\Hakudo;
5
6
use N1215\Http\RequestMatcher\RequestMatcherInterface;
7
use N1215\Http\Router\RouterInterface;
8
use N1215\Http\Router\RoutingError;
9
use N1215\Http\Router\RoutingResult;
10
use N1215\Http\Router\RoutingResultInterface;
11
use N1215\Jugoya\RequestHandlerFactoryInterface;
12
use Psr\Http\Message\ServerRequestInterface;
13
14
class Router implements RouterInterface
15
{
16
    /**
17
     * @var Route[]
18
     */
19
    private $routes;
20
21
    /**
22
     * @var RequestHandlerFactoryInterface
23
     */
24
    private $factory;
25
26 2
    public function __construct(RequestHandlerFactoryInterface $factory)
27
    {
28 2
        $this->factory = $factory;
29 2
        $this->routes = [];
30 2
    }
31
32 2
    private function addRoute(Route $route)
33
    {
34 2
        $this->routes[] = $route;
35 2
    }
36
37 2
    public function add(string $name, RequestMatcherInterface $matcher, $coreHandlerRef, array $middlewareRefs = [])
38
    {
39 2
        $handler = $this->factory->create($coreHandlerRef, $middlewareRefs);
40 2
        $this->addRoute(new Route($name, $matcher, $handler));
41 2
    }
42
43 2
    public function match(ServerRequestInterface $request): RoutingResultInterface
44
    {
45 2
        foreach ($this->routes as $route) {
46
47 2
            $requestMatchResult = $route->match($request);
48
49 2
            if ($requestMatchResult->isSuccess()) {
50 1
                return RoutingResult::success(
51 1
                    $route->getHandler(),
52 1
                    $requestMatchResult->getParams()
53
                );
54
            }
55
        }
56
57 1
        return RoutingResult::failure(new RoutingError(404, 'route not found'));
58
    }
59
}
60