1 | <?php |
||
7 | class Response |
||
8 | { |
||
9 | /** |
||
10 | * @var int |
||
11 | */ |
||
12 | private $statusCode = 0; |
||
13 | |||
14 | /** |
||
15 | * @var array |
||
16 | */ |
||
17 | private $data = []; |
||
18 | |||
19 | /** |
||
20 | * Response constructor. |
||
21 | * @param int $statusCode |
||
22 | * @param string $json |
||
23 | */ |
||
24 | 84 | public function __construct($statusCode, $json = '{}') |
|
29 | |||
30 | /** |
||
31 | * @return null|string |
||
32 | */ |
||
33 | 24 | public function getError() |
|
34 | { |
||
35 | 24 | if ($this->statusCode < 400) { |
|
36 | 3 | return null; |
|
37 | } |
||
38 | |||
39 | 21 | $messagePieces = [$this->get('message')]; |
|
40 | 21 | if ($this->get('cause')) { |
|
41 | 6 | $messagePieces = array_merge($messagePieces, $this->parseCauses($this->get('cause'))); |
|
42 | } |
||
43 | |||
44 | 21 | return join(' - ', $messagePieces); |
|
45 | } |
||
46 | |||
47 | /** |
||
48 | * @param array $cause |
||
49 | * @return array |
||
50 | */ |
||
51 | 6 | private function parseCauses(array $cause) |
|
52 | { |
||
53 | 6 | $pieces = []; |
|
54 | |||
55 | 6 | if (is_array($cause) && array_key_exists('code', $cause) && array_key_exists('description', $cause)) { |
|
56 | 3 | $pieces[] = $cause['code'] . ': ' . $cause['description']; |
|
57 | 3 | } elseif (is_array($cause)) { |
|
58 | 3 | foreach ($cause as $causes) { |
|
59 | 3 | if (is_array($causes)) { |
|
60 | 3 | foreach ($causes as $cause) { |
|
61 | 3 | $pieces[] = $cause['code'] . ': ' . $cause['description']; |
|
62 | } |
||
63 | } else { |
||
64 | 3 | $pieces[] = $causes['code'] . ': ' . $causes['description']; |
|
65 | } |
||
66 | } |
||
67 | } |
||
68 | |||
69 | 6 | return $pieces; |
|
70 | } |
||
71 | |||
72 | /** |
||
73 | * @return int |
||
74 | */ |
||
75 | 33 | public function getStatusCode() |
|
79 | |||
80 | /** |
||
81 | * @return array |
||
82 | */ |
||
83 | 48 | public function getData() |
|
87 | |||
88 | /** |
||
89 | * @return bool |
||
90 | */ |
||
91 | 69 | public function isError() |
|
95 | |||
96 | /** |
||
97 | * @param $key |
||
98 | * @param null $default |
||
99 | * @return array|mixed|null |
||
100 | */ |
||
101 | 36 | public function get($key, $default = null) |
|
102 | { |
||
103 | 36 | $keys = explode('.', (string)$key); |
|
104 | 36 | $array = &$this->data; |
|
105 | 36 | foreach ($keys as $key) { |
|
106 | 36 | if (!$this->exists($array, $key)) { |
|
107 | 3 | return $default; |
|
108 | } |
||
109 | 36 | $array = &$array[$key]; |
|
110 | } |
||
111 | |||
112 | 36 | return $array; |
|
113 | } |
||
114 | |||
115 | /** |
||
116 | * @param $array |
||
117 | * @param $key |
||
118 | * @return bool |
||
119 | */ |
||
120 | 36 | public function exists($array, $key) |
|
130 | } |
||
131 |