Deserializer.php 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294
  1. <?php
  2. namespace GuzzleHttp\Command\Guzzle;
  3. use GuzzleHttp\Command\CommandInterface;
  4. use GuzzleHttp\Command\Guzzle\ResponseLocation\BodyLocation;
  5. use GuzzleHttp\Command\Guzzle\ResponseLocation\HeaderLocation;
  6. use GuzzleHttp\Command\Guzzle\ResponseLocation\JsonLocation;
  7. use GuzzleHttp\Command\Guzzle\ResponseLocation\ReasonPhraseLocation;
  8. use GuzzleHttp\Command\Guzzle\ResponseLocation\ResponseLocationInterface;
  9. use GuzzleHttp\Command\Guzzle\ResponseLocation\StatusCodeLocation;
  10. use GuzzleHttp\Command\Guzzle\ResponseLocation\XmlLocation;
  11. use GuzzleHttp\Command\Result;
  12. use GuzzleHttp\Command\ResultInterface;
  13. use Psr\Http\Message\RequestInterface;
  14. use Psr\Http\Message\ResponseInterface;
  15. /**
  16. * Handler used to create response models based on an HTTP response and
  17. * a service description.
  18. *
  19. * Response location visitors are registered with this Handler to handle
  20. * locations (e.g., 'xml', 'json', 'header'). All of the locations of a response
  21. * model that will be visited first have their ``before`` method triggered.
  22. * After the before method is called on every visitor that will be walked, each
  23. * visitor is triggered using the ``visit()`` method. After all of the visitors
  24. * are visited, the ``after()`` method is called on each visitor. This is the
  25. * place in which you should handle things like additionalProperties with
  26. * custom locations (i.e., this is how it is handled in the JSON visitor).
  27. */
  28. class Deserializer
  29. {
  30. /** @var ResponseLocationInterface[] $responseLocations */
  31. private $responseLocations;
  32. /** @var DescriptionInterface $description */
  33. private $description;
  34. /** @var boolean $process */
  35. private $process;
  36. /**
  37. * @param DescriptionInterface $description
  38. * @param bool $process
  39. * @param ResponseLocationInterface[] $responseLocations Extra response locations
  40. */
  41. public function __construct(
  42. DescriptionInterface $description,
  43. $process,
  44. array $responseLocations = []
  45. ) {
  46. static $defaultResponseLocations;
  47. if (!$defaultResponseLocations) {
  48. $defaultResponseLocations = [
  49. 'body' => new BodyLocation(),
  50. 'header' => new HeaderLocation(),
  51. 'reasonPhrase' => new ReasonPhraseLocation(),
  52. 'statusCode' => new StatusCodeLocation(),
  53. 'xml' => new XmlLocation(),
  54. 'json' => new JsonLocation(),
  55. ];
  56. }
  57. $this->responseLocations = $responseLocations + $defaultResponseLocations;
  58. $this->description = $description;
  59. $this->process = $process;
  60. }
  61. /**
  62. * Deserialize the response into the specified result representation
  63. *
  64. * @param ResponseInterface $response
  65. * @param RequestInterface|null $request
  66. * @param CommandInterface $command
  67. * @return Result|ResultInterface|void|ResponseInterface
  68. */
  69. public function __invoke(ResponseInterface $response, RequestInterface $request, CommandInterface $command)
  70. {
  71. // If the user don't want to process the result, just return the plain response here
  72. if ($this->process === false) {
  73. return $response;
  74. }
  75. $name = $command->getName();
  76. $operation = $this->description->getOperation($name);
  77. $this->handleErrorResponses($response, $request, $command, $operation);
  78. // Add a default Model as the result if no matching schema was found
  79. if (!($modelName = $operation->getResponseModel())) {
  80. // Not sure if this should be empty or contains the response.
  81. // Decided to do it how it was in the old version for now.
  82. return new Result();
  83. }
  84. $model = $operation->getServiceDescription()->getModel($modelName);
  85. if (!$model) {
  86. throw new \RuntimeException("Unknown model: {$modelName}");
  87. }
  88. return $this->visit($model, $response);
  89. }
  90. /**
  91. * Handles visit() and after() methods of the Response locations
  92. *
  93. * @param Parameter $model
  94. * @param ResponseInterface $response
  95. * @return Result|ResultInterface|void
  96. */
  97. protected function visit(Parameter $model, ResponseInterface $response)
  98. {
  99. $result = new Result();
  100. $context = ['visitors' => []];
  101. if ($model->getType() === 'object') {
  102. $result = $this->visitOuterObject($model, $result, $response, $context);
  103. } elseif ($model->getType() === 'array') {
  104. $result = $this->visitOuterArray($model, $result, $response, $context);
  105. } else {
  106. throw new \InvalidArgumentException('Invalid response model: ' . $model->getType());
  107. }
  108. // Call the after() method of each found visitor
  109. /** @var ResponseLocationInterface $visitor */
  110. foreach ($context['visitors'] as $visitor) {
  111. $result = $visitor->after($result, $response, $model);
  112. }
  113. return $result;
  114. }
  115. /**
  116. * Handles the before() method of Response locations
  117. *
  118. * @param string $location
  119. * @param Parameter $model
  120. * @param ResultInterface $result
  121. * @param ResponseInterface $response
  122. * @param array $context
  123. * @return ResultInterface
  124. */
  125. private function triggerBeforeVisitor(
  126. $location,
  127. Parameter $model,
  128. ResultInterface $result,
  129. ResponseInterface $response,
  130. array &$context
  131. ) {
  132. if (!isset($this->responseLocations[$location])) {
  133. throw new \RuntimeException("Unknown location: $location");
  134. }
  135. $context['visitors'][$location] = $this->responseLocations[$location];
  136. $result = $this->responseLocations[$location]->before(
  137. $result,
  138. $response,
  139. $model
  140. );
  141. return $result;
  142. }
  143. /**
  144. * Visits the outer object
  145. *
  146. * @param Parameter $model
  147. * @param ResultInterface $result
  148. * @param ResponseInterface $response
  149. * @param array $context
  150. * @return ResultInterface
  151. */
  152. private function visitOuterObject(
  153. Parameter $model,
  154. ResultInterface $result,
  155. ResponseInterface $response,
  156. array &$context
  157. ) {
  158. $parentLocation = $model->getLocation();
  159. // If top-level additionalProperties is a schema, then visit it
  160. $additional = $model->getAdditionalProperties();
  161. if ($additional instanceof Parameter) {
  162. // Use the model location if none set on additionalProperties.
  163. $location = $additional->getLocation() ?: $parentLocation;
  164. $result = $this->triggerBeforeVisitor($location, $model, $result, $response, $context);
  165. }
  166. // Use 'location' from all individual defined properties, but fall back
  167. // to the model location if no per-property location is set. Collect
  168. // the properties that need to be visited into an array.
  169. $visitProperties = [];
  170. foreach ($model->getProperties() as $schema) {
  171. $location = $schema->getLocation() ?: $parentLocation;
  172. if ($location) {
  173. $visitProperties[] = [$location, $schema];
  174. // Trigger the before method on each unique visitor location
  175. if (!isset($context['visitors'][$location])) {
  176. $result = $this->triggerBeforeVisitor($location, $model, $result, $response, $context);
  177. }
  178. }
  179. }
  180. // Actually visit each response element
  181. foreach ($visitProperties as $property) {
  182. $result = $this->responseLocations[$property[0]]->visit($result, $response, $property[1]);
  183. }
  184. return $result;
  185. }
  186. /**
  187. * Visits the outer array
  188. *
  189. * @param Parameter $model
  190. * @param ResultInterface $result
  191. * @param ResponseInterface $response
  192. * @param array $context
  193. * @return ResultInterface|void
  194. */
  195. private function visitOuterArray(
  196. Parameter $model,
  197. ResultInterface $result,
  198. ResponseInterface $response,
  199. array &$context
  200. ) {
  201. // Use 'location' defined on the top of the model
  202. if (!($location = $model->getLocation())) {
  203. return;
  204. }
  205. // Trigger the before method on each unique visitor location
  206. if (!isset($context['visitors'][$location])) {
  207. $result = $this->triggerBeforeVisitor($location, $model, $result, $response, $context);
  208. }
  209. // Visit each item in the response
  210. $result = $this->responseLocations[$location]->visit($result, $response, $model);
  211. return $result;
  212. }
  213. /**
  214. * Reads the "errorResponses" from commands, and trigger appropriate exceptions
  215. *
  216. * In order for the exception to be properly triggered, all your exceptions must be instance
  217. * of "GuzzleHttp\Command\Exception\CommandException". If that's not the case, your exceptions will be wrapped
  218. * around a CommandException
  219. *
  220. * @param ResponseInterface $response
  221. * @param RequestInterface $request
  222. * @param CommandInterface $command
  223. * @param Operation $operation
  224. */
  225. protected function handleErrorResponses(
  226. ResponseInterface $response,
  227. RequestInterface $request,
  228. CommandInterface $command,
  229. Operation $operation
  230. ) {
  231. $errors = $operation->getErrorResponses();
  232. // We iterate through each errors in service description. If the descriptor contains both a phrase and
  233. // status code, there must be an exact match of both. Otherwise, a match of status code is enough
  234. $bestException = null;
  235. foreach ($errors as $error) {
  236. $code = (int) $error['code'];
  237. if ($response->getStatusCode() !== $code) {
  238. continue;
  239. }
  240. if (isset($error['phrase']) && ! ($error['phrase'] === $response->getReasonPhrase())) {
  241. continue;
  242. }
  243. $bestException = $error['class'];
  244. // If there is an exact match of phrase + code, then we cannot find a more specialized exception in
  245. // the array, so we can break early instead of iterating the remaining ones
  246. if (isset($error['phrase'])) {
  247. break;
  248. }
  249. }
  250. if (null !== $bestException) {
  251. throw new $bestException($response->getReasonPhrase(), $command, null, $request, $response);
  252. }
  253. // If we reach here, no exception could be match from descriptor, and Guzzle exception will propagate if
  254. // option "http_errors" is set to true, which is the default setting.
  255. }
  256. }