|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
declare(strict_types=1); |
|
4
|
|
|
|
|
5
|
|
|
namespace Hyde\Foundation\Kernel; |
|
6
|
|
|
|
|
7
|
|
|
use Hyde\Foundation\Concerns\BaseFoundationCollection; |
|
8
|
|
|
use Hyde\Framework\Exceptions\RouteNotFoundException; |
|
9
|
|
|
use Hyde\Pages\Concerns\HydePage; |
|
10
|
|
|
use Hyde\Support\Models\Route; |
|
11
|
|
|
|
|
12
|
|
|
/** |
|
13
|
|
|
* The RouteCollection contains all the routes, making it the Pseudo-Router for Hyde. |
|
14
|
|
|
* |
|
15
|
|
|
* @template T of \Hyde\Support\Models\Route |
|
16
|
|
|
* @template-extends \Hyde\Foundation\Concerns\BaseFoundationCollection<string, T> |
|
17
|
|
|
* |
|
18
|
|
|
* @property array<string, Route> $items The routes in the collection. |
|
19
|
|
|
* |
|
20
|
|
|
* This class is stored as a singleton in the HydeKernel. |
|
21
|
|
|
* You would commonly access it via the facade or Hyde helper: |
|
22
|
|
|
* |
|
23
|
|
|
* @see \Hyde\Foundation\Facades\Router |
|
24
|
|
|
* @see \Hyde\Hyde::routes() |
|
25
|
|
|
*/ |
|
26
|
|
|
final class RouteCollection extends BaseFoundationCollection |
|
27
|
|
|
{ |
|
28
|
|
|
public function addRoute(Route $route): void |
|
29
|
|
|
{ |
|
30
|
|
|
$this->put($route->getRouteKey(), $route); |
|
|
|
|
|
|
31
|
|
|
} |
|
32
|
|
|
|
|
33
|
|
|
protected function runDiscovery(): void |
|
34
|
|
|
{ |
|
35
|
|
|
$this->kernel->pages()->each(function (HydePage $page): void { |
|
36
|
|
|
$this->addRoute(new Route($page)); |
|
37
|
|
|
}); |
|
38
|
|
|
} |
|
39
|
|
|
|
|
40
|
|
|
protected function runExtensionCallbacks(): void |
|
41
|
|
|
{ |
|
42
|
|
|
foreach ($this->kernel->getExtensions() as $extension) { |
|
43
|
|
|
$extension->discoverRoutes($this); |
|
44
|
|
|
} |
|
45
|
|
|
} |
|
46
|
|
|
|
|
47
|
|
|
public function getRoute(string $routeKey): Route |
|
48
|
|
|
{ |
|
49
|
|
|
return $this->get($routeKey) ?? throw new RouteNotFoundException(message: "Route [$routeKey] not found in route collection"); |
|
50
|
|
|
} |
|
51
|
|
|
|
|
52
|
|
|
/** |
|
53
|
|
|
* @param class-string<\Hyde\Pages\Concerns\HydePage>|null $pageClass |
|
|
|
|
|
|
54
|
|
|
* @return \Hyde\Foundation\Kernel\RouteCollection<string, \Hyde\Support\Models\Route> |
|
55
|
|
|
*/ |
|
56
|
|
|
public function getRoutes(?string $pageClass = null): RouteCollection |
|
57
|
|
|
{ |
|
58
|
|
|
return $pageClass ? $this->filter(function (Route $route) use ($pageClass): bool { |
|
59
|
|
|
return $route->getPage() instanceof $pageClass; |
|
60
|
|
|
}) : $this; |
|
61
|
|
|
} |
|
62
|
|
|
} |
|
63
|
|
|
|