Test Failed
Push — develop ( acdfb2...2de2bf )
by nguereza
02:53
created

Application   A

Complexity

Total Complexity 12

Size/Duplication

Total Lines 143
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
eloc 39
c 0
b 0
f 0
dl 0
loc 143
rs 10
wmc 12

9 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 5 1
A handle() 0 11 2
A loadConfiguredMiddlewares() 0 9 2
A isEmptyResponse() 0 4 2
A execute() 0 3 1
A use() 0 7 1
A addMiddlerware() 0 5 1
A run() 0 12 1
A setRouting() 0 12 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 Application.php
34
 *
35
 *  The Platine Application class
36
 *
37
 *  @package    Platine\Framework\App
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\App;
49
50
use Platine\Config\Config;
51
use Platine\Framework\Http\Emitter\EmitterInterface;
52
use Platine\Framework\Http\Exception\HttpNotFoundException;
53
use Platine\Http\Handler\CallableResolverInterface;
54
use Platine\Http\Handler\MiddlewareInterface;
55
use Platine\Http\Handler\RequestHandlerInterface;
56
use Platine\Http\ResponseInterface;
57
use Platine\Http\ServerRequest;
58
use Platine\Http\ServerRequestInterface;
59
use Platine\Route\Router;
60
61
/**
62
 * class Application
63
 * @package Platine\Framework\App
64
 */
65
class Application extends AbstractApplication implements RequestHandlerInterface
66
{
67
68
    /**
69
     * The router instance
70
     * @var Router
71
     */
72
    protected Router $router;
73
74
    /**
75
     * The list of middlewares
76
     * @var MiddlewareInterface[]
77
     */
78
    protected array $middlewares = [];
79
80
    /**
81
     * Create new instance
82
     * @param string|null $basePath
83
     */
84
    public function __construct(?string $basePath = null)
85
    {
86
        parent::__construct($basePath);
87
        $this->loadConfiguredMiddlewares();
88
        $this->setRouting();
89
    }
90
91
    /**
92
     * Add new middleware in the list
93
     * @param  mixed $middleware
94
     * @return self
95
     */
96
    public function use($middleware): self
97
    {
98
        /** @var CallableResolverInterface $resolver */
99
        $resolver = $this->get(CallableResolverInterface::class);
100
        $this->middlewares[] = $resolver->resolve($middleware);
101
102
        return $this;
103
    }
104
105
    /**
106
     * Add new middleware in the list
107
     * @param  MiddlewareInterface $middleware
108
     * @return self
109
     */
110
    public function addMiddlerware(MiddlewareInterface $middleware): self
111
    {
112
        $this->middlewares[] = $middleware;
113
114
        return $this;
115
    }
116
117
    /**
118
     * Run the application
119
     * @param ServerRequestInterface|null $request
120
     * @return void
121
     */
122
    public function run(?ServerRequestInterface $request = null): void
123
    {
124
        $req = $request ?? ServerRequest::createFromGlobals();
125
        /** @var EmitterInterface $emitter */
126
        $emitter = $this->get(EmitterInterface::class);
127
        $response = $this->handle($req);
128
129
        $emitter->emit(
130
            $response,
131
            !$this->isEmptyResponse(
132
                $req->getMethod(),
133
                $response->getStatusCode()
134
            )
135
        );
136
    }
137
138
    /**
139
     * Handle the request and generate response
140
     * @param ServerRequestInterface $request
141
     * @return ResponseInterface
142
     */
143
    public function handle(ServerRequestInterface $request): ResponseInterface
144
    {
145
        $handler = clone $this;
146
        if (key($handler->middlewares) === null) {
147
            throw new HttpNotFoundException($request);
148
        }
149
150
        $middleware = current($handler->middlewares);
151
        next($handler->middlewares);
152
153
        return $middleware->process($request, $handler);
154
    }
155
156
    /**
157
     * {@inheritdoc}
158
     */
159
    public function execute(): void
160
    {
161
        $this->run();
162
    }
163
164
    /**
165
     * Set routing information
166
     * @return void
167
     */
168
    protected function setRouting(): void
169
    {
170
        $router = new Router();
171
        $router->setBasePath($this->basePath);
172
173
        $routes = $this->config->get('routes', []);
174
        //TODO find a way to remove return of array for
175
        //routes configuration
176
        $routes[0]($router);
177
178
        $this->router = $router;
179
        $this->instance($this->router);
180
    }
181
182
    /**
183
     * Load configured middlewares
184
     * @return void
185
     */
186
    protected function loadConfiguredMiddlewares(): void
187
    {
188
        /** @var Config $config */
189
        $config = $this->get(Config::class);
190
191
        /** @var string[] $middlewares */
192
        $middlewares = $config->get('middlewares', []);
193
        foreach ($middlewares as $middleware) {
194
            $this->use($middleware);
195
        }
196
    }
197
198
    /**
199
     * Whether is the response with no body
200
     * @param string $method
201
     * @param int $statusCode
202
     * @return bool
203
     */
204
    private function isEmptyResponse(string $method, int $statusCode): bool
205
    {
206
        return (strtoupper($method) === 'HEAD')
207
                || (in_array($statusCode, [100, 101, 102, 204, 205, 304], true));
208
    }
209
}
210