Router::__construct()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 1
c 1
b 0
f 0
dl 0
loc 3
rs 10
cc 1
nc 1
nop 1
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Furious\Router;
6
7
use Furious\Router\Collection\RouteCollection;
8
use Furious\Router\Exception\RequestNotMatchedException;
9
use Furious\Router\Exception\UnableToFoundRouteException;
10
use Furious\Router\Match\RouteMatch;
11
use Furious\Router\Route\RouteInterface;
12
use Psr\Http\Message\ServerRequestInterface;
13
14
class Router implements RouterInterface
15
{
16
    private RouteCollection $routes;
17
18
    /**
19
     * Router constructor.
20
     * @param RouteCollection $routes
21
     */
22
    public function __construct(RouteCollection $routes)
23
    {
24
        $this->routes = $routes;
25
    }
26
27
    /**
28
     * @return RouteCollection
29
     */
30
    public function getRouteCollection(): RouteCollection
31
    {
32
        return $this->routes;
33
    }
34
35
    public function generate(string $name, array $params = []): string
36
    {
37
        $routes = $this->routes->getRoutes();
38
39
        foreach ($routes as $route) {
40
            $url = $route->generate($name, array_filter($params));
41
            if (null !== $url) {
42
                return $url;
43
            }
44
        }
45
46
        throw new UnableToFoundRouteException($name, $params);
47
    }
48
49
    public function match(ServerRequestInterface $request): RouteMatch
50
    {
51
        $routes = $this->routes->getRoutes();
52
53
        foreach ($routes as $route) {
54
            if ($result = $route->match($request)) {
55
                return $result;
56
            }
57
        }
58
59
        throw new RequestNotMatchedException($request);
60
    }
61
62
    public function addRoute(RouteInterface $route): void
63
    {
64
        $this->routes->add($route);
65
    }
66
}