1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
/** |
4
|
|
|
* This file is part of coisa/http. |
5
|
|
|
* |
6
|
|
|
* (c) Felipe Sayão Lobato Abreu <[email protected]> |
7
|
|
|
* |
8
|
|
|
* This source file is subject to the license that is bundled |
9
|
|
|
* with this source code in the file LICENSE. |
10
|
|
|
*/ |
11
|
|
|
|
12
|
|
|
declare(strict_types=1); |
13
|
|
|
|
14
|
|
|
namespace CoiSA\Http\Middleware; |
15
|
|
|
|
16
|
|
|
use Psr\EventDispatcher\EventDispatcherInterface; |
17
|
|
|
use Psr\Http\Message\ResponseInterface; |
18
|
|
|
use Psr\Http\Message\ServerRequestInterface; |
19
|
|
|
use Psr\Http\Server\MiddlewareInterface; |
20
|
|
|
use Psr\Http\Server\RequestHandlerInterface; |
21
|
|
|
|
22
|
|
|
/** |
23
|
|
|
* Class ErrorHandlerMiddleware |
24
|
|
|
* |
25
|
|
|
* @package CoiSA\Http\Middleware |
26
|
|
|
*/ |
27
|
|
|
final class ErrorHandlerMiddleware implements MiddlewareInterface |
28
|
|
|
{ |
29
|
|
|
/** |
30
|
|
|
* @var RequestHandlerInterface |
31
|
|
|
*/ |
32
|
|
|
private $handler; |
33
|
|
|
|
34
|
|
|
/** |
35
|
|
|
* @var EventDispatcherInterface |
36
|
|
|
*/ |
37
|
|
|
private $eventDispatcher; |
38
|
|
|
|
39
|
|
|
/** |
40
|
|
|
* ErrorHandlerMiddleware constructor. |
41
|
|
|
* |
42
|
|
|
* @param RequestHandlerInterface $handler |
43
|
|
|
* @param EventDispatcherInterface $eventDispatcher |
44
|
|
|
*/ |
45
|
4 |
|
public function __construct(RequestHandlerInterface $handler, EventDispatcherInterface $eventDispatcher) |
46
|
|
|
{ |
47
|
4 |
|
$this->handler = $handler; |
48
|
4 |
|
$this->eventDispatcher = $eventDispatcher; |
49
|
4 |
|
} |
50
|
|
|
|
51
|
|
|
/** |
52
|
|
|
* {@inheritdoc} |
53
|
|
|
*/ |
54
|
3 |
|
public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface |
55
|
|
|
{ |
56
|
|
|
try { |
57
|
3 |
|
return $handler->handle($request); |
58
|
1 |
|
} catch (\Throwable $throwable) { |
59
|
1 |
|
$errorRequest = $request->withAttribute( |
60
|
1 |
|
self::class, |
61
|
1 |
|
$throwable |
62
|
|
|
); |
63
|
|
|
|
64
|
1 |
|
$this->eventDispatcher->dispatch($throwable); |
65
|
|
|
|
66
|
1 |
|
return $this->handler->handle($errorRequest); |
67
|
|
|
} |
68
|
|
|
} |
69
|
|
|
} |
70
|
|
|
|