RouterCollection::match()   A
last analyzed

Complexity

Conditions 4
Paths 4

Size

Total Lines 19

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 19
rs 9.6333
c 0
b 0
f 0
cc 4
nc 4
nop 2
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
15
class RouterCollection implements RouterInterface
16
{
17
    private const ROUTE_NOT_FOUND = 'page://self/__route_not_found';
18
19
    /** @var RouterInterface[] */
20
    private $routers;
21
22
    /**
23
     * @param RouterInterface[] $routers
24
     */
25
    public function __construct(array $routers)
26
    {
27
        $this->routers = $routers;
28
    }
29
30
    /**
31
     * {@inheritdoc}
32
     */
33
    public function match(array $globals, array $server)
34
    {
35
        foreach ($this->routers as $route) {
36
            try {
37
                $match = $route->match($globals, $server);
38
            } catch (Throwable $e) {
39
                $e = new RouterException($e->getMessage(), (int) $e->getCode(), $e->getPrevious());
40
                error_log((string) $e);
41
42
                return $this->routeNotFound();
43
            }
44
45
            if (! $match instanceof NullMatch) {
46
                return $match;
47
            }
48
        }
49
50
        return $this->routeNotFound();
51
    }
52
53
    /**
54
     * {@inheritdoc}
55
     */
56
    public function generate($name, $data)
57
    {
58
        foreach ($this->routers as $route) {
59
            $uri = $route->generate($name, $data);
60
            if ($uri) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $uri of type false|string is loosely compared to true; this is ambiguous if the string can be empty. You might want to explicitly use !== false instead.

In PHP, under loose comparison (like ==, or !=, or switch conditions), values of different types might be equal.

For string values, the empty string '' is a special case, in particular the following results might be unexpected:

''   == false // true
''   == null  // true
'ab' == false // false
'ab' == null  // false

// It is often better to use strict comparison
'' === false // false
'' === null  // false
Loading history...
61
                return $uri;
62
            }
63
        }
64
65
        return false;
66
    }
67
68
    private function routeNotFound(): RouterMatch
69
    {
70
        $routeMatch = new RouterMatch();
71
        $routeMatch->method = 'get';
72
        $routeMatch->path = self::ROUTE_NOT_FOUND;
73
74
        return $routeMatch;
75
    }
76
}
77