1 <?php
2
3 namespace RetailCrm\Response;
4
5 use RetailCrm\Exception\InvalidJsonException;
6
7 8 9
10 class ApiResponse implements \ArrayAccess
11 {
12
13 protected $statusCode;
14
15
16 protected $response;
17
18 public function __construct($statusCode, $responseBody = null)
19 {
20 $this->statusCode = (int) $statusCode;
21
22 if (!empty($responseBody)) {
23 $response = json_decode($responseBody, true);
24
25 if (!$response && JSON_ERROR_NONE !== ($error = json_last_error())) {
26 throw new InvalidJsonException(
27 "Invalid JSON in the API response body. Error code #$error",
28 $error
29 );
30 }
31
32 $this->response = $response;
33 }
34 }
35
36 37 38 39 40
41 public function getStatusCode()
42 {
43 return $this->statusCode;
44 }
45
46 47 48 49 50
51 public function isSuccessful()
52 {
53 return $this->statusCode < 400;
54 }
55
56 57 58 59 60 61
62 public function __call($name, $arguments)
63 {
64
65 $propertyName = strtolower(substr($name, 3, 1)) . substr($name, 4);
66
67 if (!isset($this->response[$propertyName])) {
68 throw new \InvalidArgumentException("Method \"$name\" not found");
69 }
70
71 return $this->response[$propertyName];
72 }
73
74 75 76 77 78 79
80 public function __get($name)
81 {
82 if (!isset($this->response[$name])) {
83 throw new \InvalidArgumentException("Property \"$name\" not found");
84 }
85
86 return $this->response[$name];
87 }
88
89 90 91 92
93 public function offsetSet($offset, $value)
94 {
95 throw new \BadMethodCallException('This activity not allowed');
96 }
97
98 99 100
101 public function offsetUnset($offset)
102 {
103 throw new \BadMethodCallException('This call not allowed');
104 }
105
106 107 108 109
110 public function offsetExists($offset)
111 {
112 return isset($this->response[$offset]);
113 }
114
115 116 117 118
119 public function offsetGet($offset)
120 {
121 if (!isset($this->response[$offset])) {
122 throw new \InvalidArgumentException("Property \"$offset\" not found");
123 }
124
125 return $this->response[$offset];
126 }
127 }