Code Coverage |
||||||||||
Lines |
Functions and Methods |
Classes and Traits |
||||||||
| Total | |
100.00% |
17 / 17 |
|
100.00% |
1 / 1 |
CRAP | |
100.00% |
1 / 1 |
| RouteDispatcherServiceProvider | |
100.00% |
17 / 17 |
|
100.00% |
1 / 1 |
6 | |
100.00% |
1 / 1 |
| register | |
100.00% |
17 / 17 |
|
100.00% |
1 / 1 |
2 | |||
| generateRouting | n/a |
0 / 0 |
n/a |
0 / 0 |
4 | |||||
| 1 | <?php |
| 2 | |
| 3 | declare(strict_types=1); |
| 4 | |
| 5 | namespace Engelsystem\Middleware; |
| 6 | |
| 7 | use Engelsystem\Config\Config; |
| 8 | use Engelsystem\Container\ServiceProvider; |
| 9 | use Engelsystem\Plugins\Plugin; |
| 10 | use FastRoute\Dispatcher as FastRouteDispatcher; |
| 11 | use FastRoute\RouteCollector; |
| 12 | use Psr\Http\Server\MiddlewareInterface; |
| 13 | |
| 14 | use function FastRoute\cachedDispatcher as FRCashedDispatcher; |
| 15 | |
| 16 | class RouteDispatcherServiceProvider extends ServiceProvider |
| 17 | { |
| 18 | public function register(): void |
| 19 | { |
| 20 | /** @var Config $config */ |
| 21 | $config = $this->app->get('config'); |
| 22 | |
| 23 | $options = [ |
| 24 | 'cacheFile' => $this->app->get('path.cache.routes'), |
| 25 | ]; |
| 26 | |
| 27 | if ($config->get('environment') == 'development') { |
| 28 | $options['cacheDisabled'] = true; |
| 29 | } |
| 30 | |
| 31 | $this->app->alias(RouteDispatcher::class, 'route.dispatcher'); |
| 32 | |
| 33 | $this->app |
| 34 | ->when(RouteDispatcher::class) |
| 35 | ->needs(FastRouteDispatcher::class) |
| 36 | ->give(function () use ($options) { |
| 37 | return $this->generateRouting($options); |
| 38 | }); |
| 39 | |
| 40 | $this->app |
| 41 | ->when(RouteDispatcher::class) |
| 42 | ->needs(MiddlewareInterface::class) |
| 43 | ->give(LegacyMiddleware::class); |
| 44 | } |
| 45 | |
| 46 | /** |
| 47 | * Includes the routes.php file |
| 48 | * |
| 49 | * @codeCoverageIgnore |
| 50 | */ |
| 51 | protected function generateRouting(array $options = []): FastRouteDispatcher |
| 52 | { |
| 53 | $routesFile = config_path('routes.php'); |
| 54 | $routesCacheFile = $this->app->get('path.cache.routes'); |
| 55 | |
| 56 | if ( |
| 57 | file_exists($routesCacheFile) |
| 58 | && filemtime($routesFile) > filemtime($routesCacheFile) |
| 59 | ) { |
| 60 | unlink($routesCacheFile); |
| 61 | } |
| 62 | |
| 63 | return FRCashedDispatcher(function (RouteCollector $route): void { |
| 64 | require config_path('routes.php'); |
| 65 | |
| 66 | /** @var Plugin $plugin */ |
| 67 | foreach ($this->app->tagged('plugin') as $plugin) { |
| 68 | $plugin->loadRoutes($route); |
| 69 | } |
| 70 | }, $options); |
| 71 | } |
| 72 | } |