1
|
|
|
<?php |
2
|
|
|
namespace Loevgaard\Consignor\ShipmentServer\Response; |
3
|
|
|
|
4
|
|
|
use ArrayAccess; |
5
|
|
|
use BadMethodCallException; |
6
|
|
|
use Loevgaard\Consignor\ShipmentServer\Request\RequestInterface; |
7
|
|
|
use Psr\Http\Message\ResponseInterface as PsrResponseInterface; |
8
|
|
|
use function Loevgaard\Consignor\ShipmentServer\decodeJson; |
9
|
|
|
|
10
|
|
|
class Response implements ResponseInterface, ArrayAccess |
11
|
|
|
{ |
12
|
|
|
/** |
13
|
|
|
* @var PsrResponseInterface |
14
|
|
|
*/ |
15
|
|
|
protected $response; |
16
|
|
|
|
17
|
|
|
/** |
18
|
|
|
* @var RequestInterface |
19
|
|
|
*/ |
20
|
|
|
protected $request; |
21
|
|
|
|
22
|
|
|
/** |
23
|
|
|
* @var array |
24
|
|
|
*/ |
25
|
|
|
protected $data; |
26
|
|
|
|
27
|
|
|
public function __construct(PsrResponseInterface $response, RequestInterface $request) |
28
|
|
|
{ |
29
|
|
|
$this->response = $response; |
30
|
|
|
$this->request = $request; |
31
|
|
|
$this->data = decodeJson((string)$this->response->getBody()); |
32
|
|
|
} |
33
|
|
|
|
34
|
|
|
public function __toString(): string |
35
|
|
|
{ |
36
|
|
|
return (string)$this->response->getBody(); |
37
|
|
|
} |
38
|
|
|
|
39
|
|
|
public function wasSuccessful() : bool |
40
|
|
|
{ |
41
|
|
|
return !isset($this->data['ErrorMessages']) && $this->response->getStatusCode() >= 200 && $this->response->getStatusCode() < 300; |
42
|
|
|
} |
43
|
|
|
|
44
|
|
|
public function getErrors() : array |
45
|
|
|
{ |
46
|
|
|
if (!isset($this->data['ErrorMessages']) || !is_array($this->data['ErrorMessages'])) { |
47
|
|
|
return []; |
48
|
|
|
} |
49
|
|
|
|
50
|
|
|
return $this->data['ErrorMessages']; |
51
|
|
|
} |
52
|
|
|
|
53
|
|
|
public function offsetExists($offset) |
54
|
|
|
{ |
55
|
|
|
return isset($this->data[$offset]); |
56
|
|
|
} |
57
|
|
|
|
58
|
|
|
public function offsetGet($offset) |
59
|
|
|
{ |
60
|
|
|
return $this->data[$offset] ?? null; |
61
|
|
|
} |
62
|
|
|
|
63
|
|
|
public function offsetSet($offset, $value) |
64
|
|
|
{ |
65
|
|
|
throw new BadMethodCallException('The response data can not be manipulated'); |
66
|
|
|
} |
67
|
|
|
|
68
|
|
|
public function offsetUnset($offset) |
69
|
|
|
{ |
70
|
|
|
throw new BadMethodCallException('The response data can not be manipulated'); |
71
|
|
|
} |
72
|
|
|
} |
73
|
|
|
|