1
|
|
|
<?php |
2
|
|
|
namespace Axado; |
3
|
|
|
|
4
|
|
|
use Axado\Exception\DestinationNotFoundException; |
5
|
|
|
use Axado\Exception\OriginNotFoundException; |
6
|
|
|
use Axado\Exception\ShippingException; |
7
|
|
|
|
8
|
|
|
class Response |
9
|
|
|
{ |
10
|
|
|
/** |
11
|
|
|
* Relevant errors from Axado API that are mapped to exceptions. |
12
|
|
|
* |
13
|
|
|
* @var array |
14
|
|
|
*/ |
15
|
|
|
private static $translatedErrors = [ |
16
|
|
|
101 => OriginNotFoundException::class, |
17
|
|
|
102 => DestinationNotFoundException::class, |
18
|
|
|
]; |
19
|
|
|
|
20
|
|
|
/** |
21
|
|
|
* Array of Axado\Quotation. |
22
|
|
|
* |
23
|
|
|
* @var array |
24
|
|
|
*/ |
25
|
|
|
protected $quotations = []; |
26
|
|
|
|
27
|
|
|
/** |
28
|
|
|
* Getter for quotations. |
29
|
|
|
* |
30
|
|
|
* @return array |
31
|
|
|
*/ |
32
|
|
|
public function quotations(): array |
33
|
|
|
{ |
34
|
|
|
return $this->quotations; |
35
|
|
|
} |
36
|
|
|
|
37
|
|
|
/** |
38
|
|
|
* Parse the raw response to this object. |
39
|
|
|
* |
40
|
|
|
* @param array|null $raw |
41
|
|
|
*/ |
42
|
|
|
public function parse($raw = null) |
43
|
|
|
{ |
44
|
|
|
$arrayResponse = (array) $raw; |
45
|
|
|
$this->checkForErrors($arrayResponse); |
46
|
|
|
|
47
|
|
|
$this->parseQuotations($arrayResponse); |
48
|
|
|
} |
49
|
|
|
|
50
|
|
|
/** |
51
|
|
|
* Verify if this Response has an error. |
52
|
|
|
* |
53
|
|
|
* @throws ShippingException |
54
|
|
|
* |
55
|
|
|
* @param array $arrayResponse |
56
|
|
|
*/ |
57
|
|
|
protected function checkForErrors($arrayResponse) |
58
|
|
|
{ |
59
|
|
|
if ($errorId = $arrayResponse['erro_id'] ?? null) { |
60
|
|
|
$exceptionClass = static::$translatedErrors[$errorId] ?? ShippingException::class; |
|
|
|
|
61
|
|
|
|
62
|
|
|
throw new $exceptionClass($arrayResponse['erro_msg'], $errorId); |
63
|
|
|
} |
64
|
|
|
} |
65
|
|
|
|
66
|
|
|
/** |
67
|
|
|
* Parse the response into Quotation objects. |
68
|
|
|
* |
69
|
|
|
* @param array $arrayResponse |
70
|
|
|
*/ |
71
|
|
|
protected function parseQuotations(array $arrayResponse) |
72
|
|
|
{ |
73
|
|
|
$quotationsArray = $arrayResponse['cotacoes'] ?? []; |
74
|
|
|
|
75
|
|
|
foreach ($quotationsArray as $quotationData) { |
76
|
|
|
$quotation = new Quotation(); |
77
|
|
|
$quotation->fill($quotationData); |
78
|
|
|
$this->quotations[] = $quotation; |
79
|
|
|
} |
80
|
|
|
} |
81
|
|
|
} |
82
|
|
|
|
Let’s assume you have a class which uses late-static binding:
The code above will run fine in your PHP runtime. However, if you now create a sub-class and call the
getSomeVariable()
on that sub-class, you will receive a runtime error:In the case above, it makes sense to update
SomeClass
to useself
instead: