RouterCollection   A
last analyzed

Complexity

Total Complexity 9

Size/Duplication

Total Lines 54
Duplicated Lines 0 %

Importance

Changes 2
Bugs 0 Features 0
Metric Value
wmc 9
eloc 20
dl 0
loc 54
rs 10
c 2
b 0
f 0

4 Methods

Rating   Name   Duplication   Size   Complexity  
A routeNotFound() 0 3 1
A __construct() 0 3 1
A match() 0 20 4
A generate() 0 11 3
1
<?php
2
3
declare(strict_types=1);
4
5
namespace BEAR\Package\Provide\Router;
6
7
use BEAR\Package\Exception\RouterException;
8
use BEAR\Sunday\Extension\Router\NullMatch;
9
use BEAR\Sunday\Extension\Router\RouterInterface;
10
use BEAR\Sunday\Extension\Router\RouterMatch;
11
use Override;
12
use Throwable;
13
14
use function error_log;
15
use function is_string;
16
17
final class RouterCollection implements RouterInterface
18
{
19
    private const ROUTE_NOT_FOUND = 'page://self/__route_not_found';
20
21
    /** @param RouterInterface[] $routers */
22
    public function __construct(
23
        private array $routers,
24
    ) {
25
    }
26
27
    /**
28
     * {@inheritDoc}
29
     */
30
    #[Override]
31
    public function match(array $globals, array $server)
32
    {
33
        foreach ($this->routers as $route) {
34
            try {
35
                $match = $route->match($globals, $server);
36
            } catch (Throwable $e) {
37
                $e = new RouterException($e->getMessage(), (int) $e->getCode(), $e->getPrevious());
38
                /** @noinspection ForgottenDebugOutputInspection */
39
                error_log((string) $e);
40
41
                return $this->routeNotFound();
42
            }
43
44
            if (! $match instanceof NullMatch) {
45
                return $match;
46
            }
47
        }
48
49
        return $this->routeNotFound();
50
    }
51
52
    /**
53
     * {@inheritDoc}
54
     */
55
    #[Override]
56
    public function generate($name, $data)
57
    {
58
        foreach ($this->routers as $route) {
59
            $uri = $route->generate($name, $data);
60
            if (is_string($uri)) {
61
                return $uri;
62
            }
63
        }
64
65
        return false;
66
    }
67
68
    private function routeNotFound(): RouterMatch
69
    {
70
        return new RouterMatch('get', self::ROUTE_NOT_FOUND, []);
71
    }
72
}
73