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