summaryrefslogtreecommitdiff
path: root/src/Middleware/RouteDispatcherServiceProvider.php
blob: 193510f39286d52cccd556697deb67b125c412d9 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
<?php

namespace Engelsystem\Middleware;

use Engelsystem\Config\Config;
use Engelsystem\Container\ServiceProvider;
use FastRoute\Dispatcher as FastRouteDispatcher;
use FastRoute\RouteCollector;
use Psr\Http\Server\MiddlewareInterface;

class RouteDispatcherServiceProvider extends ServiceProvider
{
    public function register()
    {
        /** @var Config $config */
        $config = $this->app->get('config');

        $options = [
            'cacheFile' => $this->app->get('path.cache.routes'),
        ];

        if ($config->get('environment') == 'development') {
            $options['cacheDisabled'] = true;
        }

        $this->app->alias(RouteDispatcher::class, 'route.dispatcher');

        $this->app
            ->when(RouteDispatcher::class)
            ->needs(FastRouteDispatcher::class)
            ->give(function () use ($options) {
                return $this->generateRouting($options);
            });

        $this->app
            ->when(RouteDispatcher::class)
            ->needs(MiddlewareInterface::class)
            ->give(LegacyMiddleware::class);
    }

    /**
     * Includes the routes.php file
     *
     * @param array $options
     * @return FastRouteDispatcher
     * @codeCoverageIgnore
     */
    protected function generateRouting(array $options = [])
    {
        $routesFile = config_path('routes.php');
        $routesCacheFile = $this->app->get('path.cache.routes');

        if (
            file_exists($routesCacheFile)
            && filemtime($routesFile) > filemtime($routesCacheFile)
        ) {
            unlink($routesCacheFile);
        }

        return \FastRoute\cachedDispatcher(function (RouteCollector $route) {
            require config_path('routes.php');
        }, $options);
    }
}