Passed
Push — develop ( b729b4...acdfb2 )
by nguereza
42:48
created

Application::setRouting()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 13
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 7
dl 0
loc 13
rs 10
c 0
b 0
f 0
cc 1
nc 1
nop 0
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
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;
49
50
use Platine\Framework\Http\Emitter\EmitterInterface;
51
use Platine\Framework\Http\Exception\HttpNotFoundException;
52
use Platine\Http\Handler\CallableResolverInterface;
53
use Platine\Http\Handler\MiddlewareInterface;
54
use Platine\Http\Handler\RequestHandlerInterface;
55
use Platine\Http\ResponseInterface;
56
use Platine\Http\ServerRequest;
57
use Platine\Http\ServerRequestInterface;
58
use Platine\Route\Middleware\RouteDispatcherMiddleware;
59
use Platine\Route\Middleware\RouteMatchMiddleware;
60
use Platine\Route\Router;
61
62
/**
63
 * class Application
64
 * @package Platine\Framework
65
 */
66
class Application extends AbstractApplication 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 string|null $basePath
84
     */
85
    public function __construct(?string $basePath = null)
86
    {
87
        parent::__construct($basePath);
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
126
        $routeMatcher = $this->make(RouteMatchMiddleware::class);
127
        $routeDispatcher = $this->make(RouteDispatcherMiddleware::class);
128
129
        $this->addMiddlerware($routeMatcher);
130
        $this->addMiddlerware($routeDispatcher);
131
132
        /** @var EmitterInterface $emitter */
133
        $emitter = $this->get(EmitterInterface::class);
134
        $response = $this->handle($req);
135
136
        $emitter->emit(
137
            $response,
138
            !$this->isEmptyResponse(
139
                $req->getMethod(),
140
                $response->getStatusCode()
141
            )
142
        );
143
    }
144
145
    /**
146
     * Handle the request and generate response
147
     * @param ServerRequestInterface $request
148
     * @return ResponseInterface
149
     */
150
    public function handle(ServerRequestInterface $request): ResponseInterface
151
    {
152
        $handler = clone $this;
153
        if (key($handler->middlewares) === null) {
154
            throw new HttpNotFoundException($request);
155
        }
156
157
        $middleware = current($handler->middlewares);
158
        next($handler->middlewares);
159
160
        return $middleware->process($request, $handler);
161
    }
162
163
    /**
164
     * {@inheritdoc}
165
     */
166
    public function execute(): void
167
    {
168
        $this->run();
169
    }
170
171
    /**
172
     * Set routing information
173
     * @return void
174
     */
175
    protected function setRouting(): void
176
    {
177
        $router = new Router();
178
        $router->setBasePath($this->basePath);
179
180
        $routes = static function (Router $router): void {
181
            $router->get('/tnh', MyRequestHandler::class, 'home');
182
        }; //Come from config [routes.php]
183
184
        $routes($router);
185
186
        $this->router = $router;
187
        $this->instance($this->router);
188
    }
189
190
    /**
191
     * Whether is the response with no body
192
     * @param string $method
193
     * @param int $statusCode
194
     * @return bool
195
     */
196
    private function isEmptyResponse(string $method, int $statusCode): bool
197
    {
198
        return (strtoupper($method) === 'HEAD')
199
                || (in_array($statusCode, [100, 101, 102, 204, 205, 304], true));
200
    }
201
}
202