Completed
Push — master ( b9d832...421ea6 )
by Phil
06:19 queued 04:14
created

Exception::getJsonResponse()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 9
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 5
CRAP Score 1

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 9
ccs 5
cts 5
cp 1
rs 9.6667
cc 1
eloc 5
nc 1
nop 0
crap 1
1
<?php
2
3
namespace League\Route\Http;
4
5
use League\Route\Http\Exception\HttpExceptionInterface;
6
use Psr\Http\Message\ResponseInterface;
7
8
class Exception extends \Exception implements HttpExceptionInterface
9
{
10
    /**
11
     * @var array
12
     */
13
    protected $headers = [];
14
15
    /**
16
     * @var string
17
     */
18
    protected $message;
19
20
    /**
21
     * @var integer
22
     */
23
    protected $status;
24
25
    /**
26
     * Constructor.
27
     *
28
     * @param integer    $status
29
     * @param string     $message
30
     * @param \Exception $previous
31
     * @param array      $headers
32
     * @param integer    $code
33
     */
34 66
    public function __construct(
35
        $status,
36
        $message             = null,
37
        \Exception $previous = null,
38
        array $headers       = [],
39
        $code                = 0
40
    ) {
41 66
        $this->headers = $headers;
42 66
        $this->message = $message;
43 66
        $this->status  = $status;
44
45 66
        parent::__construct($message, $code, $previous);
46 66
    }
47
48
    /**
49
     * {@inheritdoc}
50
     */
51 54
    public function getStatusCode()
52
    {
53 54
        return $this->status;
54
    }
55
56
    /**
57
     * {@inheritdoc}
58
     */
59 3
    public function getHeaders()
60
    {
61 3
        return $this->headers;
62
    }
63
64
    /**
65
     * {@inheritdoc}
66
     */
67 60
    public function buildJsonResponse(ResponseInterface $response)
68
    {
69 60
        $this->headers['content-type'] = 'application/json';
70
71 60
        foreach ($this->headers as $key => $value) {
72 60
            $response = $response->withAddedHeader($key, $value);
73 60
        }
74
75 60
        if ($response->getBody()->isWritable()) {
76 60
            $response->getBody()->write(json_encode([
77 60
                'status_code'   => $this->status,
78 60
                'reason_phrase' => $this->message
79 60
            ]));
80 60
        }
81
82 60
        return $response->withStatus($this->status, $this->message);
83
    }
84
}
85