1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
declare(strict_types=1); |
4
|
|
|
|
5
|
|
|
namespace App\Infrastructure\Http; |
6
|
|
|
|
7
|
|
|
use HttpSoft\Basis\Response\ExtractErrorDataTrait; |
8
|
|
|
use HttpSoft\ErrorHandler\ErrorResponseGeneratorInterface; |
9
|
|
|
use HttpSoft\Message\Response; |
10
|
|
|
use Psr\Http\Message\ResponseInterface; |
11
|
|
|
use Psr\Http\Message\ServerRequestInterface; |
12
|
|
|
use RuntimeException; |
13
|
|
|
use Throwable; |
14
|
|
|
use Whoops\Handler\JsonResponseHandler; |
15
|
|
|
use Whoops\Handler\PrettyPageHandler; |
16
|
|
|
use Whoops\RunInterface; |
17
|
|
|
use Whoops\Run; |
18
|
|
|
|
19
|
|
|
use function class_exists; |
20
|
|
|
|
21
|
|
|
final class WhoopsErrorResponseGenerator implements ErrorResponseGeneratorInterface |
22
|
|
|
{ |
23
|
|
|
use ExtractErrorDataTrait; |
24
|
|
|
|
25
|
|
|
/** |
26
|
|
|
* @var RunInterface |
27
|
|
|
*/ |
28
|
|
|
private RunInterface $whoops; |
29
|
|
|
|
30
|
|
|
/** |
31
|
|
|
* @param RunInterface|null $whoops |
32
|
|
|
*/ |
33
|
2 |
|
public function __construct(RunInterface $whoops = null) |
34
|
|
|
{ |
35
|
2 |
|
if ($whoops instanceof RunInterface) { |
36
|
1 |
|
$this->whoops = $whoops; |
37
|
1 |
|
return; |
38
|
|
|
} |
39
|
|
|
|
40
|
1 |
|
if (!class_exists(Run::class)) { |
41
|
|
|
throw new RuntimeException('Class "Whoops\Run" not found.'); |
42
|
|
|
} |
43
|
|
|
|
44
|
1 |
|
$this->whoops = new Run(); |
45
|
1 |
|
$this->whoops->writeToOutput(false); |
46
|
1 |
|
$this->whoops->allowQuit(false); |
47
|
1 |
|
$this->whoops->pushHandler(new PrettyPageHandler()); |
48
|
1 |
|
$this->whoops->register(); |
49
|
|
|
} |
50
|
|
|
|
51
|
|
|
/** |
52
|
|
|
* {@inheritDoc} |
53
|
|
|
* |
54
|
|
|
* @psalm-suppress MixedAssignment |
55
|
|
|
*/ |
56
|
2 |
|
public function generate(Throwable $error, ServerRequestInterface $request): ResponseInterface |
57
|
|
|
{ |
58
|
2 |
|
$response = new Response($this->extractErrorStatusCode($error)); |
59
|
|
|
|
60
|
2 |
|
foreach ($this->whoops->getHandlers() as $handler) { |
61
|
2 |
|
if ($handler instanceof PrettyPageHandler) { |
62
|
1 |
|
$handler->addDataTable('HTTP Application Request', $this->extractRequestData($request)); |
63
|
|
|
} |
64
|
|
|
|
65
|
2 |
|
if ($handler instanceof PrettyPageHandler || $handler instanceof JsonResponseHandler) { |
66
|
2 |
|
$response = $response->withHeader('content-type', $handler->contentType()); |
67
|
|
|
} |
68
|
|
|
} |
69
|
|
|
|
70
|
2 |
|
$sendOutputFlag = $this->whoops->writeToOutput(); |
71
|
2 |
|
$this->whoops->writeToOutput(false); |
72
|
2 |
|
$response->getBody()->write($this->whoops->handleException($error)); |
73
|
2 |
|
$this->whoops->writeToOutput($sendOutputFlag); |
74
|
2 |
|
return $response; |
75
|
|
|
} |
76
|
|
|
} |
77
|
|
|
|