JsonRpcParser.php 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. <?php
  2. namespace Aws\Api\Parser;
  3. use Aws\Api\Operation;
  4. use Aws\Api\StructureShape;
  5. use Aws\Api\Service;
  6. use Aws\Result;
  7. use Aws\CommandInterface;
  8. use Psr\Http\Message\ResponseInterface;
  9. use Psr\Http\Message\StreamInterface;
  10. /**
  11. * @internal Implements JSON-RPC parsing (e.g., DynamoDB)
  12. */
  13. class JsonRpcParser extends AbstractParser
  14. {
  15. use PayloadParserTrait;
  16. /**
  17. * @param Service $api Service description
  18. * @param JsonParser $parser JSON body builder
  19. */
  20. public function __construct(Service $api, JsonParser $parser = null)
  21. {
  22. parent::__construct($api);
  23. $this->parser = $parser ?: new JsonParser();
  24. }
  25. public function __invoke(
  26. CommandInterface $command,
  27. ResponseInterface $response
  28. ) {
  29. $operation = $this->api->getOperation($command->getName());
  30. return $this->parseResponse($response, $operation);
  31. }
  32. /**
  33. * This method parses a response based on JSON RPC protocol.
  34. *
  35. * @param ResponseInterface $response the response to parse.
  36. * @param Operation $operation the operation which holds information for
  37. * parsing the response.
  38. *
  39. * @return Result
  40. */
  41. private function parseResponse(ResponseInterface $response, Operation $operation)
  42. {
  43. if (null === $operation['output']) {
  44. return new Result([]);
  45. }
  46. $outputShape = $operation->getOutput();
  47. foreach ($outputShape->getMembers() as $memberName => $memberProps) {
  48. if (!empty($memberProps['eventstream'])) {
  49. return new Result([
  50. $memberName => new EventParsingIterator(
  51. $response->getBody(),
  52. $outputShape->getMember($memberName),
  53. $this
  54. )
  55. ]);
  56. }
  57. }
  58. $result = $this->parseMemberFromStream(
  59. $response->getBody(),
  60. $operation->getOutput(),
  61. $response
  62. );
  63. return new Result(is_null($result) ? [] : $result);
  64. }
  65. public function parseMemberFromStream(
  66. StreamInterface $stream,
  67. StructureShape $member,
  68. $response
  69. ) {
  70. return $this->parser->parse($member, $this->parseJson($stream, $response));
  71. }
  72. }