Completed
Push — master ( 54b866...e9cd31 )
by Diogo Oliveira de
02:40
created

Error::setHeaderList()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 1
nc 1
nop 1
dl 0
loc 3
rs 10
c 0
b 0
f 0
1
<?php
2
3
namespace SlimX\Models;
4
5
use Psr\Http\Message\ResponseInterface;
6
use SlimX\Exceptions\ErrorCodeNotFoundException;
7
8
class Error
9
{
10
    protected $codeList;
11
    protected $headerList;
12
13
    public function __construct()
14
    {
15
        $this->codeList = [];
16
        $this->headerList = [];
17
    }
18
19
    public function handle(ResponseInterface $response, int $code)
20
    {
21
        if (isset($this->codeList[$code]) &&
22
            isset($this->codeList[$code]['status']) &&
23
            isset($this->codeList[$code]['message'])
24
        ) {
25
            $node = $this->codeList[$code];
26
            $response = $response->withStatus($node['status']);
27
            $response->getBody()->write(json_encode(['code' => $code, 'message' => $node['message']]));
28
            foreach ($this->headerList as $key => $value) {
29
                $response = $response->withAddedHeader($key, $value);
30
            }
31
32
            return $response;
33
        } else {
34
            throw new ErrorCodeNotFoundException($code);
35
        }
36
    }
37
38
    /**
39
     * Get the node with the corresponding code.
40
     *
41
     * @param int $code Code number.
42
     * @return array Corresponding element in the array.
43
     */
44
    public function getNode(int $code): array
45
    {
46
        if (isset($this->codeList[$code])) {
47
            return $this->codeList[$code];
48
        } else {
49
            throw new ErrorCodeNotFoundException($code);
50
        }
51
    }
52
53
    public function setCodeList(array $codeList)
54
    {
55
        $this->codeList = $codeList;
56
    }
57
58
    public function setHeaderList(array $headerList)
59
    {
60
        $this->headerList = $headerList;
61
    }
62
}
63