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, ?string $customMessage = null) |
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
|
|
|
$ret = ['code' => $code, 'message' => $node['message']]; |
28
|
|
|
if (null !== $customMessage) { |
29
|
|
|
$ret['customMessage'] = $customMessage; |
30
|
|
|
} |
31
|
|
|
$response->getBody()->write(json_encode($ret)); |
32
|
|
|
foreach ($this->headerList as $key => $value) { |
33
|
|
|
$response = $response->withAddedHeader($key, $value); |
34
|
|
|
} |
35
|
|
|
|
36
|
|
|
return $response; |
37
|
|
|
} else { |
38
|
|
|
throw new ErrorCodeNotFoundException($code); |
39
|
|
|
} |
40
|
|
|
} |
41
|
|
|
|
42
|
|
|
/** |
43
|
|
|
* Get the node with the corresponding code. |
44
|
|
|
* |
45
|
|
|
* @param int $code Code number. |
46
|
|
|
* @return array Corresponding element in the array. |
47
|
|
|
*/ |
48
|
|
|
public function getNode(int $code): array |
49
|
|
|
{ |
50
|
|
|
if (isset($this->codeList[$code])) { |
51
|
|
|
return $this->codeList[$code]; |
52
|
|
|
} else { |
53
|
|
|
throw new ErrorCodeNotFoundException($code); |
54
|
|
|
} |
55
|
|
|
} |
56
|
|
|
|
57
|
|
|
public function setCodeList(array $codeList) |
58
|
|
|
{ |
59
|
|
|
$this->codeList = $codeList; |
60
|
|
|
} |
61
|
|
|
|
62
|
|
|
public function setHeaderList(array $headerList) |
63
|
|
|
{ |
64
|
|
|
$this->headerList = $headerList; |
65
|
|
|
} |
66
|
|
|
} |
67
|
|
|
|