Completed
Pull Request — 2.x (#29)
by Akihito
06:51
created

TwigErrorHandler::handle()   B

Complexity

Conditions 2
Paths 2

Size

Total Lines 25
Code Lines 18

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 6

Importance

Changes 0
Metric Value
c 0
b 0
f 0
dl 0
loc 25
ccs 0
cts 24
cp 0
rs 8.8571
cc 2
eloc 18
nc 2
nop 2
crap 6
1
<?php
2
/**
3
 * This file is part of the Madapaja.TwigModule package.
4
 *
5
 * @license http://opensource.org/licenses/MIT MIT
6
 */
7
namespace Madapaja\TwigModule;
8
9
use BEAR\AppMeta\AbstractAppMeta;
10
use BEAR\Package\Provide\Error\LogRef;
11
use BEAR\Resource\Code;
12
use BEAR\Resource\Exception\BadRequestException as BadRequest;
13
use BEAR\Resource\Exception\ResourceNotFoundException as NotFound;
14
use BEAR\Sunday\Extension\Error\ErrorInterface;
15
use BEAR\Sunday\Extension\Router\RouterMatch as Request;
16
use BEAR\Sunday\Extension\Transfer\TransferInterface;
17
use Psr\Log\LoggerInterface;
18
19
final class TwigErrorHandler implements ErrorInterface
20
{
21
    /**
22
     * @var TransferInterface
23
     */
24
    private $transfer;
25
    /**
26
     * @var TwigErrorPage
27
     */
28
    private $errorPage;
29
30
    /**
31
     * @var AbstractAppMeta
32
     */
33
    private $appMeta;
34
    /**
35
     * @var LoggerInterface
36
     */
37
    private $logger;
38
39
    public function __construct(TwigErrorPage $errorPage, TransferInterface $transfer, LoggerInterface $logger)
40
    {
41
        $this->transfer = $transfer;
42
        $this->errorPage = $errorPage;
43
        $this->logger = $logger;
44
    }
45
46
    /**
47
     * {@inheritdoc}
48
     */
49
    public function handle(\Exception $e, Request $request)
50
    {
51
        unset($request);
52
        $code = $this->getCode($e);
53
        $eStr = (string) $e;
54
        $logRef = crc32($eStr);
55
        if ($code >= 500) {
56
            $this->logger->error(sprintf('logref:%s %s', $logRef, $eStr));
57
        }
58
        $this->errorPage->code = $code;
59
        $this->errorPage->body = [
60
            'status' => [
61
                'code' => $code,
62
                'message' => (new Code)->statusText[$code]
63
            ],
64
            'e' => [
65
                'code' => $e->getCode(),
66
                'class' => get_class($e),
67
                'message' => $e->getMessage()
68
            ],
69
            'logref' => (string) $logRef
70
        ];
71
72
        return $this;
73
    }
74
75
    /**
76
     * {@inheritdoc}
77
     */
78
    public function transfer()
79
    {
80
        ($this->transfer)($this->errorPage, []);
81
    }
82
83
    private function getCode(\Exception $e) : int
84
    {
85
        if ($e instanceof NotFound || $e instanceof BadRequest) {
86
            return $e->getCode();
87
        }
88
89
        return 503;
90
    }
91
}
92