Test Failed
Push — develop ( 2de2bf...7fb7cc )
by nguereza
02:31
created

HttpKernel   A

Complexity

Total Complexity 12

Size/Duplication

Total Lines 154
Duplicated Lines 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 44
c 1
b 0
f 0
dl 0
loc 154
rs 10
wmc 12

8 Methods

Rating   Name   Duplication   Size   Complexity  
A setRouting() 0 17 2
A isEmptyResponse() 0 4 2
A bootstrap() 0 5 1
A registerConfiguredMiddlewares() 0 9 2
A use() 0 7 1
A run() 0 21 1
A handle() 0 11 2
A __construct() 0 4 1
1
<?php
2
3
/**
4
 * Platine Framework
5
 *
6
 * Platine Framework is a lightweight, high-performance, simple and elegant
7
 * PHP Web framework
8
 *
9
 * This content is released under the MIT License (MIT)
10
 *
11
 * Copyright (c) 2020 Platine Framework
12
 *
13
 * Permission is hereby granted, free of charge, to any person obtaining a copy
14
 * of this software and associated documentation files (the "Software"), to deal
15
 * in the Software without restriction, including without limitation the rights
16
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
17
 * copies of the Software, and to permit persons to whom the Software is
18
 * furnished to do so, subject to the following conditions:
19
 *
20
 * The above copyright notice and this permission notice shall be included in all
21
 * copies or substantial portions of the Software.
22
 *
23
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
24
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
25
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
26
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
27
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
28
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
29
 * SOFTWARE.
30
 */
31
32
/**
33
 *  @file HttpKernel.php
34
 *
35
 *  The HTTP Kernel class
36
 *
37
 *  @package    Platine\Framework\Kernel
38
 *  @author Platine Developers team
39
 *  @copyright  Copyright (c) 2020
40
 *  @license    http://opensource.org/licenses/MIT  MIT License
41
 *  @link   http://www.iacademy.cf
42
 *  @version 1.0.0
43
 *  @filesource
44
 */
45
46
declare(strict_types=1);
47
48
namespace Platine\Framework\Kernel;
49
50
use Platine\Config\Config;
51
use Platine\Framework\App\Application;
52
use Platine\Framework\Http\Emitter\EmitterInterface;
53
use Platine\Framework\Http\Exception\HttpNotFoundException;
54
use Platine\Http\Handler\MiddlewareInterface;
55
use Platine\Http\Handler\MiddlewareResolverInterface;
56
use Platine\Http\Handler\RequestHandlerInterface;
57
use Platine\Http\ResponseInterface;
58
use Platine\Http\ServerRequest;
59
use Platine\Http\ServerRequestInterface;
60
use Platine\Route\Router;
61
62
/**
63
 * class HttpKernel
64
 * @package Platine\Framework\Kernel
65
 */
66
class HttpKernel implements RequestHandlerInterface
67
{
68
69
    /**
70
     * The router instance
71
     * @var Router
72
     */
73
    protected Router $router;
74
75
    /**
76
     * The list of middlewares
77
     * @var MiddlewareInterface[]
78
     */
79
    protected array $middlewares = [];
80
81
    /**
82
     * Application instance
83
     * @var Application
84
     */
85
    protected Application $app;
86
87
    /**
88
     * Create new instance
89
     * @param Application $app
90
     * @param Router $router
91
     */
92
    public function __construct(Application $app, Router $router)
93
    {
94
        $this->app = $app;
95
        $this->router = $router;
96
    }
97
98
    /**
99
     * Bootstrap the application
100
     * @return void
101
     */
102
    public function bootstrap(): void
103
    {
104
        $this->app->registerConfiguration();
105
        $this->app->registerConfiguredServiceProviders();
106
        $this->app->boot();
107
    }
108
109
    /**
110
     * Add new middleware in the list
111
     * @param  mixed $middleware
112
     * @return $this
113
     */
114
    public function use($middleware): self
115
    {
116
        /** @var MiddlewareResolverInterface $resolver */
117
        $resolver = $this->app->get(MiddlewareResolverInterface::class);
118
        $this->middlewares[] = $resolver->resolve($middleware);
119
120
        return $this;
121
    }
122
123
    /**
124
     * Run the kernel
125
     * @param ServerRequestInterface|null $request
126
     * @return void
127
     */
128
    public function run(?ServerRequestInterface $request = null): void
129
    {
130
        //bootstrap the application
131
        $this->bootstrap();
132
133
        //set the routing
134
        $this->setRouting();
135
136
        //Load configured middlewares
137
        $this->registerConfiguredMiddlewares();
138
139
        $req = $request ?? ServerRequest::createFromGlobals();
140
        /** @var EmitterInterface $emitter */
141
        $emitter = $this->app->get(EmitterInterface::class);
142
        $response = $this->handle($req);
143
144
        $emitter->emit(
145
            $response,
146
            !$this->isEmptyResponse(
147
                $req->getMethod(),
148
                $response->getStatusCode()
149
            )
150
        );
151
    }
152
153
    /**
154
     * Handle the request and generate response
155
     * @param ServerRequestInterface $request
156
     * @return ResponseInterface
157
     */
158
    public function handle(ServerRequestInterface $request): ResponseInterface
159
    {
160
        $handler = clone $this;
161
        if (key($handler->middlewares) === null) {
162
            throw new HttpNotFoundException($request);
163
        }
164
165
        $middleware = current($handler->middlewares);
166
        next($handler->middlewares);
167
168
        return $middleware->process($request, $handler);
169
    }
170
171
    /**
172
     * Set routing information
173
     * @return void
174
     */
175
    public function setRouting(): void
176
    {
177
        /** @template T @var Config<T> $config */
178
        $config = $this->app->get(Config::class);
179
180
        $basePath = $this->app->getBasePath();
181
        if (empty($basePath)) {
182
            $basePath = $config->get('app.base_path');
183
        }
184
        $this->router->setBasePath($basePath);
185
186
        $routes = $config->get('routes', []);
187
        //TODO find a way to remove return of array for
188
        //routes configuration
189
        $routes[0]($this->router);
190
191
        $this->app->instance($this->router);
192
    }
193
194
    /**
195
     * Load configured middlewares
196
     * @return void
197
     */
198
    protected function registerConfiguredMiddlewares(): void
199
    {
200
        /** @template T @var Config<T> $config */
201
        $config = $this->app->get(Config::class);
202
203
        /** @var string[] $middlewares */
204
        $middlewares = $config->get('middlewares', []);
205
        foreach ($middlewares as $middleware) {
206
            $this->use($middleware);
207
        }
208
    }
209
210
    /**
211
     * Whether is the response with no body
212
     * @param string $method
213
     * @param int $statusCode
214
     * @return bool
215
     */
216
    private function isEmptyResponse(string $method, int $statusCode): bool
217
    {
218
        return (strtoupper($method) === 'HEAD')
219
                || (in_array($statusCode, [100, 101, 102, 204, 205, 304], true));
220
    }
221
}
222