Test Failed
Push — master ( 22b809...326de4 )
by Brent
05:15 queued 39s
created

ErrorHandler::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 10

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 0
Metric Value
cc 1
nc 1
nop 3
dl 0
loc 10
ccs 0
cts 6
cp 0
crap 2
rs 9.9332
c 0
b 0
f 0
1
<?php
2
3
namespace Stitcher\Exception;
4
5
use Pageon\Lib\Markdown\MarkdownParser;
6
use Stitcher\Renderer\RendererFactory;
7
8
class ErrorHandler
9
{
10
    /** @var \Stitcher\Renderer\Renderer */
11
    private $renderer;
12
13
    /** @var \Pageon\Lib\Markdown\MarkdownParser */
14
    private $markdownParser;
15
16
    /** @var array */
17
    private $errorPages;
18
19
    /** @var string */
20
    private $defaultErrorPage;
21
22
    public function __construct(
23
        RendererFactory $rendererFactory,
24
        MarkdownParser $markdownParser,
25
        array $errorPages = []
26
    ) {
27
        $this->renderer = $rendererFactory->create();
28
        $this->markdownParser = $markdownParser;
29
        $this->errorPages = $errorPages;
30
        $this->defaultErrorPage = __DIR__ . '/../../static/exception.html';
31
    }
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