Completed
Push — master ( 238323...52fc21 )
by Changwan
03:17
created

HttpRouterBootstrap::boot()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

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