Result.php
3.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
<?php
namespace AlibabaCloud\Client\Result;
use Countable;
use Exception;
use ArrayAccess;
use IteratorAggregate;
use InvalidArgumentException;
use GuzzleHttp\Psr7\Response;
use Psr\Http\Message\ResponseInterface;
use AlibabaCloud\Client\Request\Request;
use AlibabaCloud\Client\Traits\HasDataTrait;
/**
* Result from Alibaba Cloud
*
* @property string|null RequestId
*
* @package AlibabaCloud\Client\Result
*/
class Result extends Response implements ArrayAccess, IteratorAggregate, Countable
{
use HasDataTrait;
/**
* Instance of the request.
*
* @var Request
*/
protected $request;
/**
* Result constructor.
*
* @param ResponseInterface $response
* @param Request $request
*/
public function __construct(ResponseInterface $response, Request $request = null)
{
parent::__construct(
$response->getStatusCode(),
$response->getHeaders(),
$response->getBody(),
$response->getProtocolVersion(),
$response->getReasonPhrase()
);
$this->request = $request;
$this->resolveData();
}
private function resolveData()
{
$content = $this->getBody()->getContents();
switch ($this->getRequestFormat()) {
case 'JSON':
$result_data = $this->jsonToArray($content);
break;
case 'XML':
$result_data = $this->xmlToArray($content);
break;
case 'RAW':
$result_data = $this->jsonToArray($content);
break;
default:
$result_data = $this->jsonToArray($content);
}
if (!$result_data) {
$result_data = [];
}
$this->dot($result_data);
}
/**
* @return string
*/
private function getRequestFormat()
{
return ($this->request instanceof Request)
? \strtoupper($this->request->format)
: 'JSON';
}
/**
* @param string $response
*
* @return array
*/
private function jsonToArray($response)
{
try {
return \GuzzleHttp\json_decode($response, true);
} catch (InvalidArgumentException $exception) {
return [];
}
}
/**
* @param string $string
*
* @return array
*/
private function xmlToArray($string)
{
try {
return json_decode(json_encode(simplexml_load_string($string)), true);
} catch (Exception $exception) {
return [];
}
}
/**
* @return string
*/
public function __toString()
{
return (string)$this->getBody();
}
/**
* @return Request
*/
public function getRequest()
{
return $this->request;
}
/**
* @codeCoverageIgnore
* @return Response
* @deprecated
*/
public function getResponse()
{
return $this;
}
/**
* @return bool
*/
public function isSuccess()
{
return 200 <= $this->getStatusCode()
&& 300 > $this->getStatusCode();
}
}