RouterCollection   A
last analyzed

Complexity

Total Complexity 9

Size/Duplication

Total Lines 52
Duplicated Lines 0 %

Importance

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

4 Methods

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