Bootstrap::setRoutes()
last analyzed

Size

Total Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
nc 1
dl 0
loc 1
ccs 0
cts 0
cp 0
c 0
b 0
f 0
1
<?php
2
namespace Wandu\Foundation\WebApp;
3
4
use Throwable;
5
use Wandu\Config\ConfigServiceProvider;
6
use Wandu\Config\Contracts\Config;
7
use Wandu\DI\ContainerInterface;
8
use Wandu\Foundation\Contracts\Bootstrap as BootstrapContract;
9
use Wandu\Foundation\WebApp\Contracts\HttpErrorHandler;
10
use Wandu\Http\Factory\ServerRequestFactory;
11
use Wandu\Http\HttpServiceProvider;
12
use Wandu\Http\Sender\ResponseSender;
13
use Wandu\Router\Contracts\Routable;
14
use Wandu\Router\Dispatcher;
15
use Wandu\Router\RouterServiceProvider;
16
17
abstract class Bootstrap implements BootstrapContract
18
{
19
    /**
20
     * {@inheritdoc}
21
     */
22
    public function providers(): array
23
    {
24
        return [
25
            new ConfigServiceProvider(),
26
            new HttpServiceProvider(),
27
            new RouterServiceProvider(),
28
        ];
29
    }
30
    
31
    /**
32
     * {@inheritdoc}
33
     */
34
    public function boot(ContainerInterface $app)
35
    {
36
        $this->registerConfiguration($app->get(Config::class));
37
    }
38
39
    /**
40
     * {@inheritdoc}
41
     */
42
    public function execute(ContainerInterface $app): int
43
    {
44
        if (!$app->has(HttpErrorHandler::class)) {
45
            $app->bind(HttpErrorHandler::class, DefaultHttpErrorHandler::class);
46
        }
47
48
        $request = $app->get(ServerRequestFactory::class)->createFromGlobals();
49
        
50
        try {
51
            $dispatcher = $app->get(Dispatcher::class);
52
            $this->setRoutes($routeCollection = $dispatcher->createRouteCollection());
53
            $response = $dispatcher->dispatch($routeCollection->compile(), $request);
54
        } catch (Throwable $exception) {
55
            // output buffer clean
56
            while (ob_get_level() > 0) {
57
                ob_end_clean();
58
            }
59
60
            $errorHandler = $app->get(HttpErrorHandler::class);
61
            $app->get(ResponseSender::class)->sendToGlobal($errorHandler->handle($request, $exception));
62
            return -1;
63
        }
64
65
        $app->get(ResponseSender::class)->sendToGlobal($response);
66
        return 0;
67
    }
68
69
    /**
70
     * @param \Wandu\Config\Contracts\Config $config
71
     */
72
    abstract public function registerConfiguration(Config $config);
73
74
    /**
75
     * @param \Wandu\Router\Contracts\Routable $router
76
     */
77
    abstract public function setRoutes(Routable $router);
78
}
79