|
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) { |
|
|
|
|
|
|
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
|
|
|
|
In PHP, under loose comparison (like
==, or!=, orswitchconditions), values of different types might be equal.For
stringvalues, the empty string''is a special case, in particular the following results might be unexpected: