Deserializer.php
9.6 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
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
<?php
namespace GuzzleHttp\Command\Guzzle;
use GuzzleHttp\Command\CommandInterface;
use GuzzleHttp\Command\Guzzle\ResponseLocation\BodyLocation;
use GuzzleHttp\Command\Guzzle\ResponseLocation\HeaderLocation;
use GuzzleHttp\Command\Guzzle\ResponseLocation\JsonLocation;
use GuzzleHttp\Command\Guzzle\ResponseLocation\ReasonPhraseLocation;
use GuzzleHttp\Command\Guzzle\ResponseLocation\ResponseLocationInterface;
use GuzzleHttp\Command\Guzzle\ResponseLocation\StatusCodeLocation;
use GuzzleHttp\Command\Guzzle\ResponseLocation\XmlLocation;
use GuzzleHttp\Command\Result;
use GuzzleHttp\Command\ResultInterface;
use Psr\Http\Message\RequestInterface;
use Psr\Http\Message\ResponseInterface;
/**
* Handler used to create response models based on an HTTP response and
* a service description.
*
* Response location visitors are registered with this Handler to handle
* locations (e.g., 'xml', 'json', 'header'). All of the locations of a response
* model that will be visited first have their ``before`` method triggered.
* After the before method is called on every visitor that will be walked, each
* visitor is triggered using the ``visit()`` method. After all of the visitors
* are visited, the ``after()`` method is called on each visitor. This is the
* place in which you should handle things like additionalProperties with
* custom locations (i.e., this is how it is handled in the JSON visitor).
*/
class Deserializer
{
/** @var ResponseLocationInterface[] */
private $responseLocations;
/** @var DescriptionInterface */
private $description;
/** @var bool */
private $process;
/**
* @param bool $process
* @param ResponseLocationInterface[] $responseLocations Extra response locations
*/
public function __construct(
DescriptionInterface $description,
$process,
array $responseLocations = []
) {
static $defaultResponseLocations;
if (!$defaultResponseLocations) {
$defaultResponseLocations = [
'body' => new BodyLocation(),
'header' => new HeaderLocation(),
'reasonPhrase' => new ReasonPhraseLocation(),
'statusCode' => new StatusCodeLocation(),
'xml' => new XmlLocation(),
'json' => new JsonLocation(),
];
}
$this->responseLocations = $responseLocations + $defaultResponseLocations;
$this->description = $description;
$this->process = $process;
}
/**
* Deserialize the response into the specified result representation
*
* @param RequestInterface|null $request
*
* @return Result|ResultInterface|void|ResponseInterface
*/
public function __invoke(ResponseInterface $response, RequestInterface $request, CommandInterface $command)
{
// If the user don't want to process the result, just return the plain response here
if ($this->process === false) {
return $response;
}
$name = $command->getName();
$operation = $this->description->getOperation($name);
$this->handleErrorResponses($response, $request, $command, $operation);
// Add a default Model as the result if no matching schema was found
if (!($modelName = $operation->getResponseModel())) {
// Not sure if this should be empty or contains the response.
// Decided to do it how it was in the old version for now.
return new Result();
}
$model = $operation->getServiceDescription()->getModel($modelName);
if (!$model) {
throw new \RuntimeException("Unknown model: {$modelName}");
}
return $this->visit($model, $response);
}
/**
* Handles visit() and after() methods of the Response locations
*
* @return Result|ResultInterface|void
*/
protected function visit(Parameter $model, ResponseInterface $response)
{
$result = new Result();
$context = ['visitors' => []];
if ($model->getType() === 'object') {
$result = $this->visitOuterObject($model, $result, $response, $context);
} elseif ($model->getType() === 'array') {
$result = $this->visitOuterArray($model, $result, $response, $context);
} else {
throw new \InvalidArgumentException('Invalid response model: '.$model->getType());
}
// Call the after() method of each found visitor
/** @var ResponseLocationInterface $visitor */
foreach ($context['visitors'] as $visitor) {
$result = $visitor->after($result, $response, $model);
}
return $result;
}
/**
* Handles the before() method of Response locations
*
* @param string $location
*
* @return ResultInterface
*/
private function triggerBeforeVisitor(
$location,
Parameter $model,
ResultInterface $result,
ResponseInterface $response,
array &$context
) {
if (!isset($this->responseLocations[$location])) {
throw new \RuntimeException("Unknown location: $location");
}
$context['visitors'][$location] = $this->responseLocations[$location];
$result = $this->responseLocations[$location]->before(
$result,
$response,
$model
);
return $result;
}
/**
* Visits the outer object
*
* @return ResultInterface
*/
private function visitOuterObject(
Parameter $model,
ResultInterface $result,
ResponseInterface $response,
array &$context
) {
$parentLocation = $model->getLocation();
// If top-level additionalProperties is a schema, then visit it
$additional = $model->getAdditionalProperties();
if ($additional instanceof Parameter) {
// Use the model location if none set on additionalProperties.
$location = $additional->getLocation() ?: $parentLocation;
$result = $this->triggerBeforeVisitor($location, $model, $result, $response, $context);
}
// Use 'location' from all individual defined properties, but fall back
// to the model location if no per-property location is set. Collect
// the properties that need to be visited into an array.
$visitProperties = [];
foreach ($model->getProperties() as $schema) {
$location = $schema->getLocation() ?: $parentLocation;
if ($location) {
$visitProperties[] = [$location, $schema];
// Trigger the before method on each unique visitor location
if (!isset($context['visitors'][$location])) {
$result = $this->triggerBeforeVisitor($location, $model, $result, $response, $context);
}
}
}
// Actually visit each response element
foreach ($visitProperties as $property) {
$result = $this->responseLocations[$property[0]]->visit($result, $response, $property[1]);
}
return $result;
}
/**
* Visits the outer array
*
* @return ResultInterface|void
*/
private function visitOuterArray(
Parameter $model,
ResultInterface $result,
ResponseInterface $response,
array &$context
) {
// Use 'location' defined on the top of the model
if (!($location = $model->getLocation())) {
return;
}
// Trigger the before method on each unique visitor location
if (!isset($context['visitors'][$location])) {
$result = $this->triggerBeforeVisitor($location, $model, $result, $response, $context);
}
// Visit each item in the response
$result = $this->responseLocations[$location]->visit($result, $response, $model);
return $result;
}
/**
* Reads the "errorResponses" from commands, and trigger appropriate exceptions
*
* In order for the exception to be properly triggered, all your exceptions must be instance
* of "GuzzleHttp\Command\Exception\CommandException". If that's not the case, your exceptions will be wrapped
* around a CommandException
*/
protected function handleErrorResponses(
ResponseInterface $response,
RequestInterface $request,
CommandInterface $command,
Operation $operation
) {
$errors = $operation->getErrorResponses();
// We iterate through each errors in service description. If the descriptor contains both a phrase and
// status code, there must be an exact match of both. Otherwise, a match of status code is enough
$bestException = null;
foreach ($errors as $error) {
$code = (int) $error['code'];
if ($response->getStatusCode() !== $code) {
continue;
}
if (isset($error['phrase']) && !($error['phrase'] === $response->getReasonPhrase())) {
continue;
}
$bestException = $error['class'];
// If there is an exact match of phrase + code, then we cannot find a more specialized exception in
// the array, so we can break early instead of iterating the remaining ones
if (isset($error['phrase'])) {
break;
}
}
if (null !== $bestException) {
throw new $bestException($response->getReasonPhrase(), $command, null, $request, $response);
}
// If we reach here, no exception could be match from descriptor, and Guzzle exception will propagate if
// option "http_errors" is set to true, which is the default setting.
}
}