ErrorResponder::__construct()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 5

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 4
CRAP Score 1

Importance

Changes 0
Metric Value
dl 0
loc 5
ccs 4
cts 4
cp 1
rs 10
c 0
b 0
f 0
cc 1
nc 1
nop 2
crap 1
1
<?php
2
namespace Germania\Responder;
3
4
use Psr\Http\Message\ResponseInterface;
5
6
class ErrorResponder extends ResponderDecoratorAbstract implements ResponderInterface
7
{
8
9
    public $debug = false;
10
11
12
    /**
13
     * @param bool|boolean       $debug     Whether to turn on debug mode
14
     * @param ResponderInterface $responder Inner ResponderInterface
15
     */
16 2
    public function __construct( bool $debug, ResponderInterface $responder )
17
    {
18 2
        parent::__construct($responder);
19 2
        $this->setDebug($debug);
20 2
    }
21
22
23
    /**
24
     * Sets the debug mode.
25
     * @param bool $debug
26
     */
27 10
    public function setDebug(bool $debug) {
28 10
        $this->debug = $debug;
29 10
        return $this;
30
    }
31
32
33
    /**
34
     * @inheritDoc
35
     */
36
    public function __invoke( $e, int $status = 500 ) : ResponseInterface
37
    {
38
        return $this->createResponse( $e, $status);
39
    }
40
41
42
    /**
43
     * @inheritDoc
44
     */
45 10
    public function createResponse( $e, int $status = 500 ) : ResponseInterface
46
    {
47 10
        if (!$e instanceOf \Throwable) {
48 2
            $msg = sprintf("Expected Throwable, got '%s'", gettype($e));
49 2
            throw new ResponderInvalidArgumentException($msg);
50
        }
51
52 8
        $exceptions = array($this->throwableToArray($e));
53 8
        while ($this->debug and $e = $e->getPrevious()) {
54 2
            $exceptions[] = $this->throwableToArray($e);
55
        }
56
57
        $result = array(
58 8
            'errors' => $exceptions
59
        );
60
61 8
        return $this->getResponder()->createResponse($result)
62 8
                                    ->withStatus($status);
63
64
    }
65
66
67
68 8
    protected function throwableToArray (\Throwable $e) : array
69
    {
70
        $result = array(
71 8
            'type'     => get_class($e),
72 8
            'message'  => $e->getMessage(),
73 8
            'code'     => $e->getCode()
74
        );
75 8
        if ($this->debug) {
76 4
            $result['location'] = sprintf("%s:%s", $e->getFile(), $e->getLine());
77
        }
78
79 8
        return $result;
80
    }
81
}
82