1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
declare(strict_types=1); |
4
|
|
|
|
5
|
|
|
namespace Skrill\Response; |
6
|
|
|
|
7
|
|
|
use Skrill\Exception\ResponseDataException; |
8
|
|
|
|
9
|
|
|
/** |
10
|
|
|
* Class to represent response data. |
11
|
|
|
* Provides two approaches: |
12
|
|
|
* * "dot" notation - $res->get('sender.iban'); |
13
|
|
|
* * property access - $res->currency_id;. |
14
|
|
|
*/ |
15
|
|
|
final class Response |
16
|
|
|
{ |
17
|
|
|
/** |
18
|
|
|
* @var array |
19
|
|
|
*/ |
20
|
|
|
private $data; |
21
|
|
|
|
22
|
|
|
/** |
23
|
|
|
* @param array $data |
24
|
|
|
*/ |
25
|
|
|
public function __construct(array $data = []) |
26
|
|
|
{ |
27
|
|
|
$this->data = $data; |
28
|
|
|
} |
29
|
|
|
|
30
|
|
|
/** |
31
|
|
|
* Get an item using "dot" notation. |
32
|
|
|
* Examples: $res->get("user.id");. |
33
|
|
|
* |
34
|
|
|
* @param string $key |
35
|
|
|
* @param mixed $default |
36
|
|
|
* |
37
|
|
|
* @return mixed |
38
|
|
|
*/ |
39
|
|
|
public function get(string $key, $default = null) |
40
|
|
|
{ |
41
|
|
|
if (0 === count($this->data)) { |
42
|
|
|
return $default; |
43
|
|
|
} |
44
|
|
|
|
45
|
|
|
if (empty($key)) { |
46
|
|
|
return $this->data; |
47
|
|
|
} |
48
|
|
|
|
49
|
|
|
if (array_key_exists($key, $this->data)) { |
50
|
|
|
return $this->data[$key]; |
51
|
|
|
} |
52
|
|
|
|
53
|
|
|
return false === strpos($key, '.') ? $default : $this->getNestedValue($key, $default); |
54
|
|
|
} |
55
|
|
|
|
56
|
|
|
/** |
57
|
|
|
* @param string $key |
58
|
|
|
* @param null $default |
|
|
|
|
59
|
|
|
* |
60
|
|
|
* @return mixed |
61
|
|
|
*/ |
62
|
|
|
private function getNestedValue(string $key, $default = null) |
63
|
|
|
{ |
64
|
|
|
$array = $this->data; |
65
|
|
|
|
66
|
|
|
foreach (explode('.', $key) as $segment) { |
67
|
|
|
if (is_array($array) && array_key_exists($segment, $array)) { |
68
|
|
|
$array = $array[$segment]; |
69
|
|
|
} else { |
70
|
|
|
return $default; |
71
|
|
|
} |
72
|
|
|
} |
73
|
|
|
|
74
|
|
|
return $array; |
75
|
|
|
} |
76
|
|
|
|
77
|
|
|
/** |
78
|
|
|
* @param string $name |
79
|
|
|
* |
80
|
|
|
* @return mixed |
81
|
|
|
*/ |
82
|
|
|
public function __get(string $name) |
83
|
|
|
{ |
84
|
|
|
if (array_key_exists($name, $this->data)) { |
85
|
|
|
return $this->data[$name]; |
86
|
|
|
} |
87
|
|
|
|
88
|
|
|
return null; |
89
|
|
|
} |
90
|
|
|
|
91
|
|
|
/** |
92
|
|
|
* @param string $name |
93
|
|
|
* |
94
|
|
|
* @return bool |
95
|
|
|
*/ |
96
|
|
|
public function __isset(string $name) |
97
|
|
|
{ |
98
|
|
|
return array_key_exists($name, $this->data); |
99
|
|
|
} |
100
|
|
|
|
101
|
|
|
/** |
102
|
|
|
* @param string $name |
103
|
|
|
* @param mixed $value |
104
|
|
|
* |
105
|
|
|
* @throws ResponseDataException |
106
|
|
|
*/ |
107
|
|
|
public function __set(string $name, $value) |
108
|
|
|
{ |
109
|
|
|
throw ResponseDataException::reedOnlyMode(); |
110
|
|
|
} |
111
|
|
|
} |
112
|
|
|
|