|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
/** |
|
4
|
|
|
* This file is part of Blitz PHP framework. |
|
5
|
|
|
* |
|
6
|
|
|
* (c) 2022 Dimitri Sitchet Tomkeu <[email protected]> |
|
7
|
|
|
* |
|
8
|
|
|
* For the full copyright and license information, please view |
|
9
|
|
|
* the LICENSE file that was distributed with this source code. |
|
10
|
|
|
*/ |
|
11
|
|
|
|
|
12
|
|
|
namespace BlitzPHP\Router; |
|
13
|
|
|
|
|
14
|
|
|
use BlitzPHP\Cache\ResponseCache; |
|
15
|
|
|
use BlitzPHP\Container\Container; |
|
16
|
|
|
use BlitzPHP\Container\Services; |
|
17
|
|
|
use BlitzPHP\Contracts\Event\EventManagerInterface; |
|
18
|
|
|
use BlitzPHP\Contracts\Http\ResponsableInterface; |
|
19
|
|
|
use BlitzPHP\Contracts\Router\RouteCollectionInterface; |
|
20
|
|
|
use BlitzPHP\Contracts\Support\Responsable; |
|
21
|
|
|
use BlitzPHP\Core\App; |
|
22
|
|
|
use BlitzPHP\Debug\Timer; |
|
23
|
|
|
use BlitzPHP\Exceptions\PageNotFoundException; |
|
24
|
|
|
use BlitzPHP\Exceptions\RedirectException; |
|
25
|
|
|
use BlitzPHP\Exceptions\ValidationException; |
|
26
|
|
|
use BlitzPHP\Http\MiddlewareQueue; |
|
27
|
|
|
use BlitzPHP\Http\MiddlewareRunner; |
|
28
|
|
|
use BlitzPHP\Http\Request; |
|
29
|
|
|
use BlitzPHP\Http\Response; |
|
30
|
|
|
use BlitzPHP\Http\Uri; |
|
31
|
|
|
use BlitzPHP\Utilities\Helpers; |
|
32
|
|
|
use BlitzPHP\Utilities\String\Text; |
|
33
|
|
|
use BlitzPHP\Validation\ErrorBag; |
|
34
|
|
|
use Closure; |
|
35
|
|
|
use Exception; |
|
36
|
|
|
use InvalidArgumentException; |
|
37
|
|
|
use Psr\Http\Message\ResponseInterface; |
|
38
|
|
|
use Psr\Http\Message\ServerRequestInterface; |
|
39
|
|
|
use stdClass; |
|
40
|
|
|
use Throwable; |
|
41
|
|
|
|
|
42
|
|
|
/** |
|
43
|
|
|
* Cette classe est la porte d'entree du framework. Elle analyse la requete, |
|
44
|
|
|
* recherche la route correspondante et invoque le bon controleurm puis renvoie la reponse. |
|
45
|
|
|
*/ |
|
46
|
|
|
class Dispatcher |
|
47
|
|
|
{ |
|
48
|
|
|
/** |
|
49
|
|
|
* Heure de démarrage de l'application. |
|
50
|
|
|
* |
|
51
|
|
|
* @var mixed |
|
52
|
|
|
*/ |
|
53
|
|
|
protected $startTime; |
|
54
|
|
|
|
|
55
|
|
|
/** |
|
56
|
|
|
* Durée totale d'exécution de l'application |
|
57
|
|
|
* |
|
58
|
|
|
* @var float |
|
59
|
|
|
*/ |
|
60
|
|
|
protected $totalTime; |
|
61
|
|
|
|
|
62
|
|
|
/** |
|
63
|
|
|
* Main application configuration |
|
64
|
|
|
* |
|
65
|
|
|
* @var stdClass |
|
66
|
|
|
*/ |
|
67
|
|
|
protected $config; |
|
68
|
|
|
|
|
69
|
|
|
/** |
|
70
|
|
|
* instance Timer. |
|
71
|
|
|
* |
|
72
|
|
|
* @var Timer |
|
73
|
|
|
*/ |
|
74
|
|
|
protected $timer; |
|
75
|
|
|
|
|
76
|
|
|
/** |
|
77
|
|
|
* requête courrante. |
|
78
|
|
|
* |
|
79
|
|
|
* @var Request |
|
80
|
|
|
*/ |
|
81
|
|
|
protected $request; |
|
82
|
|
|
|
|
83
|
|
|
/** |
|
84
|
|
|
* Reponse courrante. |
|
85
|
|
|
* |
|
86
|
|
|
* @var Response |
|
87
|
|
|
*/ |
|
88
|
|
|
protected $response; |
|
89
|
|
|
|
|
90
|
|
|
/** |
|
91
|
|
|
* Router à utiliser. |
|
92
|
|
|
* |
|
93
|
|
|
* @var Router |
|
94
|
|
|
*/ |
|
95
|
|
|
protected $router; |
|
96
|
|
|
|
|
97
|
|
|
/** |
|
98
|
|
|
* @var MiddlewareQueue |
|
99
|
|
|
*/ |
|
100
|
|
|
private $middleware; |
|
101
|
|
|
|
|
102
|
|
|
/** |
|
103
|
|
|
* Contrôleur à utiliser. |
|
104
|
|
|
* |
|
105
|
|
|
* @var (Closure(mixed...): ResponseInterface|string)|string |
|
|
|
|
|
|
106
|
|
|
*/ |
|
107
|
|
|
protected $controller; |
|
108
|
|
|
|
|
109
|
|
|
/** |
|
110
|
|
|
* Méthode du ontrôleur à exécuter. |
|
111
|
|
|
* |
|
112
|
|
|
* @var string |
|
113
|
|
|
*/ |
|
114
|
|
|
protected $method; |
|
115
|
|
|
|
|
116
|
|
|
/** |
|
117
|
|
|
* Gestionnaire de sortie à utiliser. |
|
118
|
|
|
* |
|
119
|
|
|
* @var string |
|
120
|
|
|
*/ |
|
121
|
|
|
protected $output; |
|
122
|
|
|
|
|
123
|
|
|
/** |
|
124
|
|
|
* Chemin de requête à utiliser. |
|
125
|
|
|
* |
|
126
|
|
|
* @var string |
|
127
|
|
|
* |
|
128
|
|
|
* @deprecated No longer used. |
|
129
|
|
|
*/ |
|
130
|
|
|
protected $path; |
|
131
|
|
|
|
|
132
|
|
|
/** |
|
133
|
|
|
* Niveau de mise en mémoire tampon de sortie de l'application |
|
134
|
|
|
*/ |
|
135
|
|
|
protected int $bufferLevel = 0; |
|
136
|
|
|
|
|
137
|
|
|
/** |
|
138
|
|
|
* Mise en cache des pages Web |
|
139
|
|
|
*/ |
|
140
|
|
|
protected ResponseCache $pageCache; |
|
141
|
|
|
|
|
142
|
|
|
/** |
|
143
|
|
|
* Constructeur. |
|
144
|
|
|
*/ |
|
145
|
|
|
public function __construct(protected EventManagerInterface $event, protected Container $container) |
|
146
|
|
|
{ |
|
147
|
|
|
$this->startTime = microtime(true); |
|
148
|
|
|
$this->config = (object) config('app'); |
|
|
|
|
|
|
149
|
|
|
|
|
150
|
|
|
$this->pageCache = Services::responsecache(); |
|
151
|
|
|
} |
|
152
|
|
|
|
|
153
|
|
|
/** |
|
154
|
|
|
* Retourne la methode invoquee |
|
155
|
|
|
*/ |
|
156
|
|
|
public static function getMethod(): ?string |
|
157
|
|
|
{ |
|
158
|
|
|
$method = Services::singleton(self::class)->method; |
|
159
|
|
|
if (empty($method)) { |
|
160
|
|
|
$method = Services::routes()->getDefaultMethod(); |
|
161
|
|
|
} |
|
162
|
|
|
|
|
163
|
|
|
return $method; |
|
164
|
|
|
} |
|
165
|
|
|
|
|
166
|
|
|
/** |
|
167
|
|
|
* Retourne le contrôleur utilisé |
|
168
|
|
|
* |
|
169
|
|
|
* @return Closure|string |
|
170
|
|
|
*/ |
|
171
|
|
|
public static function getController(bool $fullName = true) |
|
172
|
|
|
{ |
|
173
|
|
|
$routes = Services::routes(); |
|
174
|
|
|
|
|
175
|
|
|
$controller = Services::singleton(self::class)->controller; |
|
176
|
|
|
if (empty($controller)) { |
|
177
|
|
|
$controller = $routes->getDefaultController(); |
|
178
|
|
|
} |
|
179
|
|
|
|
|
180
|
|
|
if (! $fullName && is_string($controller)) { |
|
181
|
|
|
$controller = str_replace($routes->getDefaultNamespace(), '', $controller); |
|
182
|
|
|
} |
|
183
|
|
|
|
|
184
|
|
|
return $controller; |
|
185
|
|
|
} |
|
186
|
|
|
|
|
187
|
|
|
/** |
|
188
|
|
|
* Lancez l'application ! |
|
189
|
|
|
* |
|
190
|
|
|
* C'est "la boucle" si vous voulez. Le principal point d'entrée dans le script |
|
191
|
|
|
* qui obtient les instances de classe requises, déclenche les filtres, |
|
192
|
|
|
* essaie d'acheminer la réponse, charge le contrôleur et généralement |
|
193
|
|
|
* fait fonctionner toutes les pièces ensemble. |
|
194
|
|
|
* |
|
195
|
|
|
* @return bool|mixed|ResponseInterface|ServerRequestInterface |
|
196
|
|
|
* |
|
197
|
|
|
* @throws Exception |
|
198
|
|
|
* @throws RedirectException |
|
199
|
|
|
*/ |
|
200
|
|
|
public function run(?RouteCollectionInterface $routes = null, bool $returnResponse = false) |
|
201
|
|
|
{ |
|
202
|
|
|
$this->pageCache->setTtl(0); |
|
203
|
|
|
$this->bufferLevel = ob_get_level(); |
|
204
|
|
|
|
|
205
|
|
|
$this->startBenchmark(); |
|
206
|
|
|
|
|
207
|
|
|
$this->getRequestObject(); |
|
208
|
|
|
$this->getResponseObject(); |
|
209
|
|
|
|
|
210
|
|
|
$this->event->trigger('pre_system'); |
|
211
|
|
|
|
|
212
|
|
|
$this->timer->stop('bootstrap'); |
|
213
|
|
|
|
|
214
|
|
|
$this->initMiddlewareQueue(); |
|
215
|
|
|
|
|
216
|
|
|
try { |
|
217
|
|
|
$this->response = $this->handleRequest($routes, config('cache')); |
|
|
|
|
|
|
218
|
|
|
} catch (ResponsableInterface $e) { |
|
219
|
|
|
$this->outputBufferingEnd(); |
|
220
|
|
|
$this->response = $e->getResponse(); |
|
221
|
|
|
} catch (PageNotFoundException $e) { |
|
222
|
|
|
$this->response = $this->display404errors($e); |
|
223
|
|
|
} catch (Throwable $e) { |
|
224
|
|
|
$this->outputBufferingEnd(); |
|
225
|
|
|
|
|
226
|
|
|
throw $e; |
|
227
|
|
|
} |
|
228
|
|
|
|
|
229
|
|
|
// Y a-t-il un événement post-système ? |
|
230
|
|
|
$this->event->trigger('post_system'); |
|
231
|
|
|
|
|
232
|
|
|
if ($returnResponse) { |
|
233
|
|
|
return $this->response; |
|
234
|
|
|
} |
|
235
|
|
|
|
|
236
|
|
|
$this->sendResponse(); |
|
237
|
|
|
} |
|
238
|
|
|
|
|
239
|
|
|
/** |
|
240
|
|
|
* Gère la logique de requête principale et déclenche le contrôleur. |
|
241
|
|
|
* |
|
242
|
|
|
* @throws PageNotFoundException |
|
243
|
|
|
* @throws RedirectException |
|
244
|
|
|
*/ |
|
245
|
|
|
protected function handleRequest(?RouteCollectionInterface $routes = null, ?array $cacheConfig = null): ResponseInterface |
|
246
|
|
|
{ |
|
247
|
|
|
$routeMiddlewares = $this->dispatchRoutes($routes); |
|
248
|
|
|
|
|
249
|
|
|
/** |
|
250
|
|
|
* Ajouter des middlewares de routes |
|
251
|
|
|
*/ |
|
252
|
|
|
foreach ($routeMiddlewares as $middleware) { |
|
253
|
|
|
$this->middleware->append($middleware); |
|
254
|
|
|
} |
|
255
|
|
|
|
|
256
|
|
|
$this->middleware->append($this->bootApp()); |
|
257
|
|
|
|
|
258
|
|
|
// Enregistrer notre URI actuel en tant qu'URI précédent dans la session |
|
259
|
|
|
// pour une utilisation plus sûre et plus précise avec la fonction d'assistance `previous_url()`. |
|
260
|
|
|
$this->storePreviousURL(current_url(true)); |
|
261
|
|
|
|
|
262
|
|
|
return (new MiddlewareRunner())->run($this->middleware, $this->request); |
|
263
|
|
|
} |
|
264
|
|
|
|
|
265
|
|
|
/** |
|
266
|
|
|
* Démarrer le benchmark |
|
267
|
|
|
* |
|
268
|
|
|
* La minuterie est utilisée pour afficher l'exécution totale du script à la fois dans la |
|
269
|
|
|
* barre d'outils de débogage, et éventuellement sur la page affichée. |
|
270
|
|
|
*/ |
|
271
|
|
|
protected function startBenchmark() |
|
272
|
|
|
{ |
|
273
|
|
|
if ($this->startTime === null) { |
|
274
|
|
|
$this->startTime = microtime(true); |
|
275
|
|
|
} |
|
276
|
|
|
|
|
277
|
|
|
$this->timer = Services::timer(); |
|
278
|
|
|
$this->timer->start('total_execution', $this->startTime); |
|
|
|
|
|
|
279
|
|
|
$this->timer->start('bootstrap'); |
|
280
|
|
|
} |
|
281
|
|
|
|
|
282
|
|
|
/** |
|
283
|
|
|
* Définit un objet Request à utiliser pour cette requête. |
|
284
|
|
|
* Utilisé lors de l'exécution de certains tests. |
|
285
|
|
|
*/ |
|
286
|
|
|
public function setRequest(ServerRequestInterface $request): self |
|
287
|
|
|
{ |
|
288
|
|
|
$this->request = $request; |
|
|
|
|
|
|
289
|
|
|
|
|
290
|
|
|
return $this; |
|
291
|
|
|
} |
|
292
|
|
|
|
|
293
|
|
|
/** |
|
294
|
|
|
* Obtenez notre objet Request et définissez le protocole du serveur en fonction des informations fournies |
|
295
|
|
|
* par le serveur. |
|
296
|
|
|
*/ |
|
297
|
|
|
protected function getRequestObject() |
|
298
|
|
|
{ |
|
299
|
|
|
if ($this->request instanceof ServerRequestInterface) { |
|
|
|
|
|
|
300
|
|
|
return; |
|
301
|
|
|
} |
|
302
|
|
|
|
|
303
|
|
|
if (is_cli() && ! on_test()) { |
|
304
|
|
|
// @codeCoverageIgnoreStart |
|
305
|
|
|
// $this->request = Services::clirequest($this->config); |
|
306
|
|
|
// @codeCoverageIgnoreEnd |
|
307
|
|
|
} |
|
308
|
|
|
|
|
309
|
|
|
$version = $_SERVER['SERVER_PROTOCOL'] ?? 'HTTP/1.1'; |
|
310
|
|
|
if (! is_numeric($version)) { |
|
311
|
|
|
$version = substr($version, strpos($version, '/') + 1); |
|
312
|
|
|
} |
|
313
|
|
|
|
|
314
|
|
|
// Assurez-vous que la version est au bon format |
|
315
|
|
|
$version = number_format((float) $version, 1); |
|
316
|
|
|
|
|
317
|
|
|
$this->request = Services::request()->withProtocolVersion($version); |
|
318
|
|
|
} |
|
319
|
|
|
|
|
320
|
|
|
/** |
|
321
|
|
|
* Obtenez notre objet Response et définissez des valeurs par défaut, notamment |
|
322
|
|
|
* la version du protocole HTTP et une réponse réussie par défaut. |
|
323
|
|
|
*/ |
|
324
|
|
|
protected function getResponseObject() |
|
325
|
|
|
{ |
|
326
|
|
|
// Supposons le succès jusqu'à preuve du contraire. |
|
327
|
|
|
$this->response = Services::response()->withStatus(200); |
|
328
|
|
|
|
|
329
|
|
|
if (! is_cli() || on_test()) { |
|
330
|
|
|
} |
|
331
|
|
|
|
|
332
|
|
|
$this->response = $this->response->withProtocolVersion($this->request->getProtocolVersion()); |
|
333
|
|
|
} |
|
334
|
|
|
|
|
335
|
|
|
/** |
|
336
|
|
|
* Renvoie un tableau avec nos statistiques de performances de base collectées. |
|
337
|
|
|
*/ |
|
338
|
|
|
public function getPerformanceStats(): array |
|
339
|
|
|
{ |
|
340
|
|
|
// Après le filtre, la barre d'outils de débogage nécessite 'total_execution'. |
|
341
|
|
|
$this->totalTime = $this->timer->getElapsedTime('total_execution'); |
|
342
|
|
|
|
|
343
|
|
|
return [ |
|
344
|
|
|
'startTime' => $this->startTime, |
|
345
|
|
|
'totalTime' => $this->totalTime, |
|
346
|
|
|
]; |
|
347
|
|
|
} |
|
348
|
|
|
|
|
349
|
|
|
/** |
|
350
|
|
|
* Fonctionne avec le routeur pour |
|
351
|
|
|
* faire correspondre une route à l'URI actuel. Si la route est une |
|
352
|
|
|
* "route de redirection", gérera également la redirection. |
|
353
|
|
|
* |
|
354
|
|
|
* @param RouteCollectionInterface|null $routes Une interface de collecte à utiliser à la place |
|
355
|
|
|
* du fichier de configuration. |
|
356
|
|
|
* |
|
357
|
|
|
* @return string[] |
|
358
|
|
|
* |
|
359
|
|
|
* @throws RedirectException |
|
360
|
|
|
*/ |
|
361
|
|
|
protected function dispatchRoutes(?RouteCollectionInterface $routes = null): array |
|
362
|
|
|
{ |
|
363
|
|
|
$this->timer->start('routing'); |
|
364
|
|
|
|
|
365
|
|
|
if ($routes === null) { |
|
366
|
|
|
$routes = Services::routes()->loadRoutes(); |
|
367
|
|
|
} |
|
368
|
|
|
|
|
369
|
|
|
// $routes est defini dans app/Config/routes.php |
|
370
|
|
|
$this->router = Services::router($routes, $this->request, false); |
|
371
|
|
|
|
|
372
|
|
|
$this->outputBufferingStart(); |
|
373
|
|
|
|
|
374
|
|
|
$this->controller = $this->router->handle($this->request->getPath()); |
|
375
|
|
|
$this->method = $this->router->methodName(); |
|
376
|
|
|
|
|
377
|
|
|
// Si un segment {locale} correspondait dans la route finale, |
|
378
|
|
|
// alors nous devons définir les paramètres régionaux corrects sur notre requête. |
|
379
|
|
|
if ($this->router->hasLocale()) { |
|
380
|
|
|
$this->request = $this->request->withLocale($this->router->getLocale()); |
|
381
|
|
|
} |
|
382
|
|
|
|
|
383
|
|
|
$this->timer->stop('routing'); |
|
384
|
|
|
|
|
385
|
|
|
return $this->router->getMiddlewares(); |
|
386
|
|
|
} |
|
387
|
|
|
|
|
388
|
|
|
/** |
|
389
|
|
|
* Détermine le chemin à utiliser pour que nous essayions d'acheminer vers, en fonction |
|
390
|
|
|
* de l'entrée de l'utilisateur (setPath), ou le chemin CLI/IncomingRequest. |
|
391
|
|
|
* |
|
392
|
|
|
* @deprecated 0.10.0 |
|
393
|
|
|
*/ |
|
394
|
|
|
protected function determinePath(): string |
|
395
|
|
|
{ |
|
396
|
|
|
$path = $this->request->getPath(); |
|
397
|
|
|
|
|
398
|
|
|
return preg_replace('#^' . App::getUri()->getPath() . '#i', '', $path); |
|
399
|
|
|
} |
|
400
|
|
|
|
|
401
|
|
|
/** |
|
402
|
|
|
* Maintenant que tout a été configuré, cette méthode tente d'exécuter le |
|
403
|
|
|
* méthode du contrôleur et lancez le script. S'il n'en est pas capable, le fera |
|
404
|
|
|
* afficher l'erreur Page introuvable appropriée. |
|
405
|
|
|
*/ |
|
406
|
|
|
protected function startController() |
|
407
|
|
|
{ |
|
408
|
|
|
$this->timer->start('controller'); |
|
409
|
|
|
$this->timer->start('controller_constructor'); |
|
410
|
|
|
|
|
411
|
|
|
// Aucun contrôleur spécifié - nous ne savons pas quoi faire maintenant. |
|
412
|
|
|
if (empty($this->controller)) { |
|
413
|
|
|
throw PageNotFoundException::emptyController(); |
|
414
|
|
|
} |
|
415
|
|
|
|
|
416
|
|
|
// Est-il acheminé vers une Closure ? |
|
417
|
|
|
if (is_object($this->controller) && (get_class($this->controller) === 'Closure')) { |
|
418
|
|
|
if (empty($returned = $this->container->call($this->controller, $this->router->params()))) { |
|
|
|
|
|
|
419
|
|
|
$returned = $this->outputBufferingEnd(); |
|
420
|
|
|
} |
|
421
|
|
|
|
|
422
|
|
|
return $returned; |
|
423
|
|
|
} |
|
424
|
|
|
|
|
425
|
|
|
// Essayez de charger automatiquement la classe |
|
426
|
|
|
if (! class_exists($this->controller, true) || ($this->method[0] === '_' && $this->method !== '__invoke')) { |
|
427
|
|
|
throw PageNotFoundException::controllerNotFound($this->controller, $this->method); |
|
428
|
|
|
} |
|
429
|
|
|
|
|
430
|
|
|
return null; |
|
431
|
|
|
} |
|
432
|
|
|
|
|
433
|
|
|
/** |
|
434
|
|
|
* Instancie la classe contrôleur. |
|
435
|
|
|
* |
|
436
|
|
|
* @return \BlitzPHP\Controllers\BaseController|mixed |
|
437
|
|
|
*/ |
|
438
|
|
|
private function createController(ServerRequestInterface $request, ResponseInterface $response) |
|
439
|
|
|
{ |
|
440
|
|
|
/** |
|
441
|
|
|
* @var \BlitzPHP\Controllers\BaseController |
|
442
|
|
|
*/ |
|
443
|
|
|
$class = $this->container->get($this->controller); |
|
444
|
|
|
|
|
445
|
|
|
if (method_exists($class, 'initialize')) { |
|
446
|
|
|
$class->initialize($request, $response, Services::logger()); |
|
447
|
|
|
} |
|
448
|
|
|
|
|
449
|
|
|
$this->timer->stop('controller_constructor'); |
|
450
|
|
|
|
|
451
|
|
|
return $class; |
|
452
|
|
|
} |
|
453
|
|
|
|
|
454
|
|
|
/** |
|
455
|
|
|
* Exécute le contrôleur, permettant aux méthodes _remap de fonctionner. |
|
456
|
|
|
* |
|
457
|
|
|
* @param mixed $class |
|
458
|
|
|
* |
|
459
|
|
|
* @return mixed |
|
460
|
|
|
*/ |
|
461
|
|
|
protected function runController($class) |
|
462
|
|
|
{ |
|
463
|
|
|
$params = $this->router->params(); |
|
464
|
|
|
$method = $this->method; |
|
465
|
|
|
|
|
466
|
|
|
if (method_exists($class, '_remap')) { |
|
467
|
|
|
$params = [$method, $params]; |
|
468
|
|
|
$method = '_remap'; |
|
469
|
|
|
} |
|
470
|
|
|
|
|
471
|
|
|
if (empty($output = $this->container->call([$class, $method], $params))) { |
|
472
|
|
|
$output = $this->outputBufferingEnd(); |
|
473
|
|
|
} |
|
474
|
|
|
|
|
475
|
|
|
$this->timer->stop('controller'); |
|
476
|
|
|
|
|
477
|
|
|
return $output; |
|
478
|
|
|
} |
|
479
|
|
|
|
|
480
|
|
|
/** |
|
481
|
|
|
* Affiche une page d'erreur 404 introuvable. S'il est défini, essaiera de |
|
482
|
|
|
* appelez le contrôleur/méthode 404Override qui a été défini dans la configuration de routage. |
|
483
|
|
|
*/ |
|
484
|
|
|
protected function display404errors(PageNotFoundException $e) |
|
485
|
|
|
{ |
|
486
|
|
|
// Existe-t-il une dérogation 404 disponible ? |
|
487
|
|
|
if ($override = $this->router->get404Override()) { |
|
488
|
|
|
$returned = null; |
|
489
|
|
|
|
|
490
|
|
|
if ($override instanceof Closure) { |
|
|
|
|
|
|
491
|
|
|
echo $override($e->getMessage()); |
|
492
|
|
|
} elseif (is_array($override)) { |
|
|
|
|
|
|
493
|
|
|
$this->timer->start('controller'); |
|
494
|
|
|
$this->timer->start('controller_constructor'); |
|
495
|
|
|
|
|
496
|
|
|
$this->controller = $override[0]; |
|
497
|
|
|
$this->method = $override[1]; |
|
498
|
|
|
|
|
499
|
|
|
$controller = $this->createController($this->request, $this->response); |
|
500
|
|
|
$returned = $this->runController($controller); |
|
501
|
|
|
} |
|
502
|
|
|
|
|
503
|
|
|
unset($override); |
|
504
|
|
|
|
|
505
|
|
|
$this->gatherOutput($returned); |
|
506
|
|
|
|
|
507
|
|
|
return $this->response; |
|
508
|
|
|
} |
|
509
|
|
|
|
|
510
|
|
|
// Affiche l'erreur 404 |
|
511
|
|
|
$this->response = $this->response->withStatus($e->getCode()); |
|
512
|
|
|
|
|
513
|
|
|
$this->outputBufferingEnd(); |
|
514
|
|
|
|
|
515
|
|
|
throw PageNotFoundException::pageNotFound(! on_prod() || is_cli() ? $e->getMessage() : ''); |
|
516
|
|
|
} |
|
517
|
|
|
|
|
518
|
|
|
/** |
|
519
|
|
|
* Rassemble la sortie du script à partir du tampon, remplace certaines balises d'exécutions |
|
520
|
|
|
* d'horodatage dans la sortie et affiche la barre d'outils de débogage, si nécessaire. |
|
521
|
|
|
* |
|
522
|
|
|
* @param mixed|null $returned |
|
523
|
|
|
*/ |
|
524
|
|
|
protected function gatherOutput($returned = null) |
|
525
|
|
|
{ |
|
526
|
|
|
$this->output = $this->outputBufferingEnd(); |
|
527
|
|
|
|
|
528
|
|
|
// Si le contrôleur a renvoyé un objet de réponse, |
|
529
|
|
|
// nous devons en saisir le corps pour qu'il puisse |
|
530
|
|
|
// être ajouté à tout ce qui aurait déjà pu être ajouté avant de faire le écho. |
|
531
|
|
|
// Nous devons également enregistrer l'instance localement |
|
532
|
|
|
// afin que tout changement de code d'état, etc., ait lieu. |
|
533
|
|
|
if ($returned instanceof ResponseInterface) { |
|
534
|
|
|
$this->response = $returned; |
|
|
|
|
|
|
535
|
|
|
$returned = $returned->getBody()->getContents(); |
|
536
|
|
|
} |
|
537
|
|
|
|
|
538
|
|
|
if (is_string($returned)) { |
|
539
|
|
|
$this->output .= $returned; |
|
540
|
|
|
} |
|
541
|
|
|
|
|
542
|
|
|
$this->response = $this->response->withBody(to_stream($this->output)); |
|
543
|
|
|
} |
|
544
|
|
|
|
|
545
|
|
|
/** |
|
546
|
|
|
* Si nous avons un objet de session à utiliser, stockez l'URI actuel |
|
547
|
|
|
* comme l'URI précédent. Ceci est appelé juste avant d'envoyer la |
|
548
|
|
|
* réponse au client, et le rendra disponible à la prochaine demande. |
|
549
|
|
|
* |
|
550
|
|
|
* Cela permet au fournisseur une détection plus sûre et plus fiable de la fonction previous_url(). |
|
551
|
|
|
* |
|
552
|
|
|
* @param \BlitzPHP\Http\Uri|string $uri |
|
553
|
|
|
*/ |
|
554
|
|
|
public function storePreviousURL($uri) |
|
555
|
|
|
{ |
|
556
|
|
|
// Ignorer les requêtes CLI |
|
557
|
|
|
if (is_cli() && ! on_test()) { |
|
558
|
|
|
return; // @codeCoverageIgnore |
|
559
|
|
|
} |
|
560
|
|
|
|
|
561
|
|
|
// Ignorer les requêtes AJAX |
|
562
|
|
|
if (method_exists($this->request, 'isAJAX') && $this->request->isAJAX()) { |
|
|
|
|
|
|
563
|
|
|
return; |
|
564
|
|
|
} |
|
565
|
|
|
|
|
566
|
|
|
// Ignorer les reponses non-HTML |
|
567
|
|
|
if (! str_contains($this->response->getHeaderLine('Content-Type'), 'text/html')) { |
|
568
|
|
|
return; |
|
569
|
|
|
} |
|
570
|
|
|
|
|
571
|
|
|
// Ceci est principalement nécessaire lors des tests ... |
|
572
|
|
|
if (is_string($uri)) { |
|
573
|
|
|
$uri = Services::uri($uri, false); |
|
574
|
|
|
} |
|
575
|
|
|
|
|
576
|
|
|
Services::session()->setPreviousUrl(Uri::createURIString( |
|
577
|
|
|
$uri->getScheme(), |
|
578
|
|
|
$uri->getAuthority(), |
|
579
|
|
|
$uri->getPath(), |
|
580
|
|
|
$uri->getQuery(), |
|
581
|
|
|
$uri->getFragment() |
|
582
|
|
|
)); |
|
583
|
|
|
} |
|
584
|
|
|
|
|
585
|
|
|
/** |
|
586
|
|
|
* Renvoie la sortie de cette requête au client. |
|
587
|
|
|
* C'est ce qu'il attendait ! |
|
588
|
|
|
*/ |
|
589
|
|
|
protected function sendResponse() |
|
590
|
|
|
{ |
|
591
|
|
|
if (! ($this->request->expectsJson() || $this->request->isJson() || Text::contains($this->response->getType(), ['/json', '+json']))) { |
|
592
|
|
|
$this->response = Services::toolbar()->prepare( |
|
593
|
|
|
$this->getPerformanceStats(), |
|
594
|
|
|
$this->request, |
|
595
|
|
|
$this->response |
|
596
|
|
|
); |
|
597
|
|
|
} |
|
598
|
|
|
|
|
599
|
|
|
Services::emitter()->emit($this->response); |
|
600
|
|
|
} |
|
601
|
|
|
|
|
602
|
|
|
protected function emitResponse() |
|
603
|
|
|
{ |
|
604
|
|
|
$this->gatherOutput(); |
|
605
|
|
|
$this->sendResponse(); |
|
606
|
|
|
} |
|
607
|
|
|
|
|
608
|
|
|
/** |
|
609
|
|
|
* Construit une reponse adequate en fonction du retour du controleur |
|
610
|
|
|
* |
|
611
|
|
|
* @param mixed $returned |
|
612
|
|
|
*/ |
|
613
|
|
|
protected function formatResponse(ResponseInterface $response, $returned): ResponseInterface |
|
614
|
|
|
{ |
|
615
|
|
|
if ($returned instanceof ResponseInterface) { |
|
616
|
|
|
return $returned; |
|
617
|
|
|
} |
|
618
|
|
|
|
|
619
|
|
|
if ($returned instanceof Responsable) { |
|
620
|
|
|
return $returned->toResponse($this->request); |
|
621
|
|
|
} |
|
622
|
|
|
|
|
623
|
|
|
if (is_object($returned)) { |
|
624
|
|
|
if (method_exists($returned, '__toString')) { |
|
625
|
|
|
$returned = $returned->__toString(); |
|
626
|
|
|
} elseif (method_exists($returned, 'toArray')) { |
|
627
|
|
|
$returned = $returned->toArray(); |
|
628
|
|
|
} elseif (method_exists($returned, 'toJSON')) { |
|
629
|
|
|
$returned = $returned->toJSON(); |
|
630
|
|
|
} else { |
|
631
|
|
|
$returned = (array) $returned; |
|
632
|
|
|
} |
|
633
|
|
|
} |
|
634
|
|
|
|
|
635
|
|
|
if (is_array($returned)) { |
|
636
|
|
|
$returned = Helpers::collect($returned); |
|
637
|
|
|
$response = $response->withHeader('Content-Type', 'application/json'); |
|
638
|
|
|
} |
|
639
|
|
|
|
|
640
|
|
|
try { |
|
641
|
|
|
$response = $response->withBody(to_stream($returned)); |
|
642
|
|
|
} catch (InvalidArgumentException $e) { |
|
|
|
|
|
|
643
|
|
|
} |
|
644
|
|
|
|
|
645
|
|
|
return $response; |
|
|
|
|
|
|
646
|
|
|
} |
|
647
|
|
|
|
|
648
|
|
|
/** |
|
649
|
|
|
* Initialise le gestionnaire de middleware |
|
650
|
|
|
*/ |
|
651
|
|
|
protected function initMiddlewareQueue(): void |
|
652
|
|
|
{ |
|
653
|
|
|
$this->middleware = new MiddlewareQueue($this->container, [], $this->request, $this->response); |
|
654
|
|
|
|
|
655
|
|
|
$this->middleware->append($this->spoofRequestMethod()); |
|
656
|
|
|
$this->middleware->register(/** @scrutinizer ignore-type */ config('middlewares')); |
|
657
|
|
|
} |
|
658
|
|
|
|
|
659
|
|
|
protected function outputBufferingStart(): void |
|
660
|
|
|
{ |
|
661
|
|
|
$this->bufferLevel = ob_get_level(); |
|
662
|
|
|
|
|
663
|
|
|
ob_start(); |
|
664
|
|
|
} |
|
665
|
|
|
|
|
666
|
|
|
protected function outputBufferingEnd(): string |
|
667
|
|
|
{ |
|
668
|
|
|
$buffer = ''; |
|
669
|
|
|
|
|
670
|
|
|
while (ob_get_level() > $this->bufferLevel) { |
|
671
|
|
|
$buffer .= ob_get_contents(); |
|
672
|
|
|
ob_end_clean(); |
|
673
|
|
|
} |
|
674
|
|
|
|
|
675
|
|
|
return $buffer; |
|
676
|
|
|
} |
|
677
|
|
|
|
|
678
|
|
|
/** |
|
679
|
|
|
* Modifie l'objet de requête pour utiliser une méthode différente |
|
680
|
|
|
* si une variable POST appelée _method est trouvée. |
|
681
|
|
|
*/ |
|
682
|
|
|
private function spoofRequestMethod(): callable |
|
683
|
|
|
{ |
|
684
|
|
|
return static function (ServerRequestInterface $request, ResponseInterface $response, callable $next) { |
|
685
|
|
|
$post = $request->getParsedBody(); |
|
686
|
|
|
|
|
687
|
|
|
// Ne fonctionne qu'avec les formulaires POST |
|
688
|
|
|
if ($request->getMethod() === 'POST' && ! empty($post['_method'])) { |
|
689
|
|
|
// Accepte seulement PUT, PATCH, DELETE |
|
690
|
|
|
if (in_array($post['_method'], ['PUT', 'PATCH', 'DELETE'], true)) { |
|
691
|
|
|
$request = $request->withMethod($post['_method']); |
|
692
|
|
|
} |
|
693
|
|
|
} |
|
694
|
|
|
|
|
695
|
|
|
return $next($request, $response); |
|
696
|
|
|
}; |
|
697
|
|
|
} |
|
698
|
|
|
|
|
699
|
|
|
private function bootApp(): callable |
|
700
|
|
|
{ |
|
701
|
|
|
return function (ServerRequestInterface $request, ResponseInterface $response, callable $next): ResponseInterface { |
|
702
|
|
|
Services::set(Request::class, $request); |
|
703
|
|
|
Services::set(Response::class, $response); |
|
704
|
|
|
|
|
705
|
|
|
try { |
|
706
|
|
|
$returned = $this->startController(); |
|
707
|
|
|
|
|
708
|
|
|
// Les controleur sous forme de Closure sont executes dans startController(). |
|
709
|
|
|
if (! is_callable($this->controller)) { |
|
710
|
|
|
$controller = $this->createController($request, $response); |
|
711
|
|
|
|
|
712
|
|
|
if (! method_exists($controller, '_remap') && ! is_callable([$controller, $this->method], false)) { |
|
713
|
|
|
throw PageNotFoundException::methodNotFound($this->method); |
|
714
|
|
|
} |
|
715
|
|
|
|
|
716
|
|
|
// Y'a t-il un evenement "post_controller_constructor" |
|
717
|
|
|
$this->event->trigger('post_controller_constructor'); |
|
718
|
|
|
|
|
719
|
|
|
$returned = $this->runController($controller); |
|
720
|
|
|
} else { |
|
721
|
|
|
$this->timer->stop('controller_constructor'); |
|
722
|
|
|
$this->timer->stop('controller'); |
|
723
|
|
|
} |
|
724
|
|
|
|
|
725
|
|
|
$this->event->trigger('post_system'); |
|
726
|
|
|
|
|
727
|
|
|
return $this->formatResponse($response, $returned); |
|
728
|
|
|
} catch (ValidationException $e) { |
|
729
|
|
|
return $this->formatValidationResponse($e, $request, $response); |
|
730
|
|
|
} |
|
731
|
|
|
}; |
|
732
|
|
|
} |
|
733
|
|
|
|
|
734
|
|
|
/** |
|
735
|
|
|
* Formattage des erreurs de validation |
|
736
|
|
|
*/ |
|
737
|
|
|
private function formatValidationResponse(ValidationException $e, ServerRequestInterface $request, ResponseInterface $response): ResponseInterface |
|
738
|
|
|
{ |
|
739
|
|
|
$code = $e->getCode(); |
|
740
|
|
|
if (empty($errors = $e->getErrors())) { |
|
741
|
|
|
$errors = [$e->getMessage()]; |
|
742
|
|
|
} |
|
743
|
|
|
|
|
744
|
|
|
if (in_array($request->getMethod(), ['OPTIONS', 'HEAD'], true)) { |
|
745
|
|
|
throw $e; |
|
746
|
|
|
} |
|
747
|
|
|
|
|
748
|
|
|
if ($this->request->expectsJson() || $this->request->isJson() || Text::contains($this->response->getType(), ['/json', '+json'])) { |
|
749
|
|
|
return $this->formatResponse($response->withStatus($code), [ |
|
750
|
|
|
'success' => false, |
|
751
|
|
|
'code' => $code, |
|
752
|
|
|
'errors' => $errors instanceof ErrorBag ? $errors->all() : (array) $errors, |
|
753
|
|
|
]); |
|
754
|
|
|
} |
|
755
|
|
|
|
|
756
|
|
|
return Services::redirection()->back()->withInput()->withErrors($errors)->withStatus($code); |
|
757
|
|
|
} |
|
758
|
|
|
} |
|
759
|
|
|
|