Test Failed
Push — develop ( 833877...64b6b0 )
by nguereza
02:36
created

HttpKernel   A

Complexity

Total Complexity 11

Size/Duplication

Total Lines 137
Duplicated Lines 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 40
c 1
b 0
f 0
dl 0
loc 137
rs 10
wmc 11

7 Methods

Rating   Name   Duplication   Size   Complexity  
A setRouting() 0 17 2
A isEmptyResponse() 0 4 2
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 extends BaseKernel 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
     * Create new instance
83
     * @param Application $app
84
     * @param Router $router
85
     */
86
    public function __construct(Application $app, Router $router)
87
    {
88
        parent::__construct($app);
89
        $this->router = $router;
90
    }
91
92
    /**
93
     * Add new middleware in the list
94
     * @param  mixed $middleware
95
     * @return $this
96
     */
97
    public function use($middleware): self
98
    {
99
        /** @var MiddlewareResolverInterface $resolver */
100
        $resolver = $this->app->get(MiddlewareResolverInterface::class);
101
        $this->middlewares[] = $resolver->resolve($middleware);
102
103
        return $this;
104
    }
105
106
    /**
107
     * Run the kernel
108
     * @param ServerRequestInterface|null $request
109
     * @return void
110
     */
111
    public function run(?ServerRequestInterface $request = null): void
112
    {
113
        //bootstrap the application
114
        $this->bootstrap();
115
116
        //set the routing
117
        $this->setRouting();
118
119
        //Load configured middlewares
120
        $this->registerConfiguredMiddlewares();
121
122
        $req = $request ?? ServerRequest::createFromGlobals();
123
        /** @var EmitterInterface $emitter */
124
        $emitter = $this->app->get(EmitterInterface::class);
125
        $response = $this->handle($req);
126
127
        $emitter->emit(
128
            $response,
129
            !$this->isEmptyResponse(
130
                $req->getMethod(),
131
                $response->getStatusCode()
132
            )
133
        );
134
    }
135
136
    /**
137
     * Handle the request and generate response
138
     * @param ServerRequestInterface $request
139
     * @return ResponseInterface
140
     */
141
    public function handle(ServerRequestInterface $request): ResponseInterface
142
    {
143
        $handler = clone $this;
144
145
        $middleware = current($handler->middlewares);
146
        if ($middleware === false) {
147
            throw new HttpNotFoundException($request);
148
        }
149
        next($handler->middlewares);
150
151
        return $middleware->process($request, $handler);
152
    }
153
154
    /**
155
     * Set routing information
156
     * @return void
157
     */
158
    public function setRouting(): void
159
    {
160
        /** @template T @var Config<T> $config */
161
        $config = $this->app->get(Config::class);
162
163
        $basePath = $this->app->getBasePath();
164
        if (empty($basePath)) {
165
            $basePath = $config->get('app.base_path', '/');
166
        }
167
        $this->router->setBasePath($basePath);
168
169
        $routes = $config->get('routes', []);
170
        //TODO find a way to remove return of array for
171
        //routes configuration
172
        $routes[0]($this->router);
173
174
        $this->app->instance($this->router);
175
    }
176
177
    /**
178
     * Load configured middlewares
179
     * @return void
180
     */
181
    protected function registerConfiguredMiddlewares(): void
182
    {
183
        /** @template T @var Config<T> $config */
184
        $config = $this->app->get(Config::class);
185
186
        /** @var string[] $middlewares */
187
        $middlewares = $config->get('middlewares', []);
188
        foreach ($middlewares as $middleware) {
189
            $this->use($middleware);
190
        }
191
    }
192
193
    /**
194
     * Whether is the response with no body
195
     * @param string $method
196
     * @param int $statusCode
197
     * @return bool
198
     */
199
    private function isEmptyResponse(string $method, int $statusCode): bool
200
    {
201
        return (strtoupper($method) === 'HEAD')
202
                || (in_array($statusCode, [100, 101, 102, 204, 205, 304], true));
203
    }
204
}
205