1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
/** |
4
|
|
|
* This file is part of coisa/error-handler. |
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\ErrorHandler\Http\Middleware; |
15
|
|
|
|
16
|
|
|
use CoiSA\ErrorHandler\ErrorHandlerInterface; |
17
|
|
|
use CoiSA\ErrorHandler\Http\Message\ThrowableResponseFactoryInterface; |
18
|
|
|
use Psr\Http\Message\ResponseInterface; |
19
|
|
|
use Psr\Http\Message\ServerRequestInterface; |
20
|
|
|
use Psr\Http\Server\MiddlewareInterface; |
21
|
|
|
use Psr\Http\Server\RequestHandlerInterface; |
22
|
|
|
|
23
|
|
|
/** |
24
|
|
|
* Class ErrorHandlerMiddleware |
25
|
|
|
* |
26
|
|
|
* @package CoiSA\ErrorHandler\Middleware |
27
|
|
|
*/ |
28
|
|
|
final class ErrorHandlerMiddleware implements MiddlewareInterface |
29
|
|
|
{ |
30
|
|
|
/** |
31
|
|
|
* @var ErrorHandlerInterface |
32
|
|
|
*/ |
33
|
|
|
private $errorHandler; |
34
|
|
|
|
35
|
|
|
/** |
36
|
|
|
* @var ThrowableResponseFactoryInterface |
37
|
|
|
*/ |
38
|
|
|
private $throwableResponseFactory; |
39
|
|
|
|
40
|
|
|
/** |
41
|
|
|
* ErrorHandlerMiddleware constructor. |
42
|
|
|
* |
43
|
|
|
* @param ErrorHandlerInterface $errorHandler |
44
|
|
|
* @param ThrowableResponseFactoryInterface $throwableResponseFactory |
45
|
|
|
*/ |
46
|
6 |
|
public function __construct( |
47
|
|
|
ErrorHandlerInterface $errorHandler, |
48
|
|
|
ThrowableResponseFactoryInterface $throwableResponseFactory |
49
|
|
|
) { |
50
|
6 |
|
$this->errorHandler = $errorHandler; |
51
|
6 |
|
$this->throwableResponseFactory = $throwableResponseFactory; |
52
|
6 |
|
} |
53
|
|
|
|
54
|
|
|
/** |
55
|
|
|
* @param ServerRequestInterface $request |
56
|
|
|
* @param RequestHandlerInterface $handler |
57
|
|
|
* |
58
|
|
|
* @return ResponseInterface |
59
|
|
|
*/ |
60
|
2 |
|
public function process( |
61
|
|
|
ServerRequestInterface $request, |
62
|
|
|
RequestHandlerInterface $handler |
63
|
|
|
): ResponseInterface { |
64
|
2 |
|
$this->errorHandler->register(); |
65
|
|
|
|
66
|
|
|
try { |
67
|
2 |
|
$response = $handler->handle($request); |
68
|
2 |
|
} catch (\Throwable $throwable) { |
69
|
2 |
|
$response = $this->throwableResponseFactory->createResponseFromThrowable($throwable); |
70
|
2 |
|
} finally { |
71
|
2 |
|
$this->errorHandler->unregister(); |
72
|
|
|
} |
73
|
|
|
|
74
|
2 |
|
return $response; |
75
|
|
|
} |
76
|
|
|
} |
77
|
|
|
|