Completed
Pull Request — 2.x (#29)
by Akihito
01:35
created

TwigErrorHandler   A

Complexity

Total Complexity 7

Size/Duplication

Total Lines 69
Duplicated Lines 0 %

Coupling/Cohesion

Components 2
Dependencies 4

Test Coverage

Coverage 0%

Importance

Changes 0
Metric Value
wmc 7
lcom 2
cbo 4
dl 0
loc 69
ccs 0
cts 41
cp 0
rs 10
c 0
b 0
f 0

4 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 6 1
B handle() 0 25 2
A transfer() 0 4 1
A getCode() 0 8 3
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\Package\Provide\Error\LogRef;
10
use BEAR\Resource\Code;
11
use BEAR\Resource\Exception\BadRequestException as BadRequest;
12
use BEAR\Resource\Exception\ResourceNotFoundException as NotFound;
13
use BEAR\Sunday\Extension\Error\ErrorInterface;
14
use BEAR\Sunday\Extension\Router\RouterMatch as Request;
15
use BEAR\Sunday\Extension\Transfer\TransferInterface;
16
use Psr\Log\LoggerInterface;
17
18
final class TwigErrorHandler implements ErrorInterface
19
{
20
    /**
21
     * @var TransferInterface
22
     */
23
    private $transfer;
24
    /**
25
     * @var TwigErrorPage
26
     */
27
    private $errorPage;
28
29
    /**
30
     * @var LoggerInterface
31
     */
32
    private $logger;
33
34
    public function __construct(TwigErrorPage $errorPage, TransferInterface $transfer, LoggerInterface $logger)
35
    {
36
        $this->transfer = $transfer;
37
        $this->errorPage = $errorPage;
38
        $this->logger = $logger;
39
    }
40
41
    /**
42
     * {@inheritdoc}
43
     */
44
    public function handle(\Exception $e, Request $request)
45
    {
46
        unset($request);
47
        $code = $this->getCode($e);
48
        $eStr = (string) $e;
49
        $logRef = \crc32($eStr);
50
        if ($code >= 500) {
51
            $this->logger->error(\sprintf('logref:%s %s', $logRef, $eStr));
52
        }
53
        $this->errorPage->code = $code;
54
        $this->errorPage->body = [
55
            'status' => [
56
                'code' => $code,
57
                'message' => (new Code)->statusText[$code]
58
            ],
59
            'e' => [
60
                'code' => $e->getCode(),
61
                'class' => \get_class($e),
62
                'message' => $e->getMessage()
63
            ],
64
            'logref' => (string) $logRef
65
        ];
66
67
        return $this;
68
    }
69
70
    /**
71
     * {@inheritdoc}
72
     */
73
    public function transfer()
74
    {
75
        ($this->transfer)($this->errorPage, []);
76
    }
77
78
    private function getCode(\Exception $e) : int
79
    {
80
        if ($e instanceof NotFound || $e instanceof BadRequest) {
81
            return $e->getCode();
82
        }
83
84
        return 503;
85
    }
86
}
87