|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
namespace Stitcher\Exception; |
|
4
|
|
|
|
|
5
|
|
|
use Pageon\Lib\Parsedown; |
|
6
|
|
|
use Stitcher\Renderer\RendererFactory; |
|
7
|
|
|
|
|
8
|
|
|
class ErrorHandler |
|
9
|
|
|
{ |
|
10
|
|
|
/** @var \Stitcher\Renderer\Renderer */ |
|
11
|
|
|
private $renderer; |
|
12
|
|
|
|
|
13
|
|
|
/** @var \Pageon\Lib\Parsedown */ |
|
14
|
|
|
private $markdownParser; |
|
15
|
|
|
|
|
16
|
|
|
/** @var array */ |
|
17
|
|
|
private $errorPages; |
|
18
|
|
|
|
|
19
|
|
|
/** @var string */ |
|
20
|
|
|
private $defaultErrorPage; |
|
21
|
|
|
|
|
22
|
3 |
|
public function __construct( |
|
23
|
|
|
RendererFactory $rendererFactory, |
|
24
|
|
|
Parsedown $markdownParser, |
|
25
|
|
|
array $errorPages = [] |
|
26
|
|
|
) { |
|
27
|
3 |
|
$this->renderer = $rendererFactory->create(); |
|
28
|
3 |
|
$this->markdownParser = $markdownParser; |
|
29
|
3 |
|
$this->errorPages = $errorPages; |
|
30
|
3 |
|
$this->defaultErrorPage = __DIR__ . '/../../static/exception.html'; |
|
31
|
3 |
|
} |
|
32
|
|
|
|
|
33
|
|
|
public function handle(int $statusCode, ?StitcherException $exception = null): string |
|
34
|
|
|
{ |
|
35
|
|
|
$template = $this->errorPages[$statusCode] ?? null; |
|
36
|
|
|
|
|
37
|
|
|
if (! $template) { |
|
38
|
|
|
return $this->handleStaticError($exception); |
|
39
|
|
|
} |
|
40
|
|
|
|
|
41
|
|
|
return $this->renderer->renderTemplate($template, [ |
|
42
|
|
|
'error_title' => $this->markdownParser->parse($exception->title()), |
|
43
|
|
|
'error_body' => $this->markdownParser->parse($exception->body()), |
|
44
|
|
|
]); |
|
45
|
|
|
} |
|
46
|
|
|
|
|
47
|
|
|
private function handleStaticError(?StitcherException $exception): string |
|
48
|
|
|
{ |
|
49
|
|
|
$html = file_get_contents($this->defaultErrorPage); |
|
50
|
|
|
|
|
51
|
|
|
if (! $exception) { |
|
52
|
|
|
return $html; |
|
53
|
|
|
} |
|
54
|
|
|
|
|
55
|
|
|
$html = str_replace( |
|
56
|
|
|
['{{ title }}', '{{ body }}'], |
|
57
|
|
|
[$this->markdownParser->parse($exception->title()), $this->markdownParser->parse($exception->body())], |
|
58
|
|
|
$html |
|
59
|
|
|
); |
|
60
|
|
|
|
|
61
|
|
|
return $html; |
|
62
|
|
|
} |
|
63
|
|
|
} |
|
64
|
|
|
|