JsonBody.php 3.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108
  1. <?php
  2. namespace Aws\Api\Serializer;
  3. use Aws\Api\Service;
  4. use Aws\Api\Shape;
  5. use Aws\Api\TimestampShape;
  6. use Aws\Exception\InvalidJsonException;
  7. /**
  8. * Formats the JSON body of a JSON-REST or JSON-RPC operation.
  9. * @internal
  10. */
  11. class JsonBody
  12. {
  13. private $api;
  14. public function __construct(Service $api)
  15. {
  16. $this->api = $api;
  17. }
  18. /**
  19. * Gets the JSON Content-Type header for a service API
  20. *
  21. * @param Service $service
  22. *
  23. * @return string
  24. */
  25. public static function getContentType(Service $service)
  26. {
  27. if ($service->getMetadata('protocol') === 'rest-json') {
  28. return 'application/json';
  29. }
  30. $jsonVersion = $service->getMetadata('jsonVersion');
  31. if (empty($jsonVersion)) {
  32. throw new \InvalidArgumentException('invalid json');
  33. } else {
  34. return 'application/x-amz-json-'
  35. . @number_format($service->getMetadata('jsonVersion'), 1);
  36. }
  37. }
  38. /**
  39. * Builds the JSON body based on an array of arguments.
  40. *
  41. * @param Shape $shape Operation being constructed
  42. * @param array $args Associative array of arguments
  43. *
  44. * @return string
  45. */
  46. public function build(Shape $shape, array $args)
  47. {
  48. $result = json_encode($this->format($shape, $args));
  49. return $result == '[]' ? '{}' : $result;
  50. }
  51. private function format(Shape $shape, $value)
  52. {
  53. switch ($shape['type']) {
  54. case 'structure':
  55. $data = [];
  56. if (isset($shape['document']) && $shape['document']) {
  57. return $value;
  58. }
  59. foreach ($value as $k => $v) {
  60. if ($v !== null && $shape->hasMember($k)) {
  61. $valueShape = $shape->getMember($k);
  62. $data[$valueShape['locationName'] ?: $k]
  63. = $this->format($valueShape, $v);
  64. }
  65. }
  66. if (empty($data)) {
  67. return new \stdClass;
  68. }
  69. return $data;
  70. case 'list':
  71. $items = $shape->getMember();
  72. foreach ($value as $k => $v) {
  73. $value[$k] = $this->format($items, $v);
  74. }
  75. return $value;
  76. case 'map':
  77. if (empty($value)) {
  78. return new \stdClass;
  79. }
  80. $values = $shape->getValue();
  81. foreach ($value as $k => $v) {
  82. $value[$k] = $this->format($values, $v);
  83. }
  84. return $value;
  85. case 'blob':
  86. return base64_encode($value);
  87. case 'timestamp':
  88. $timestampFormat = !empty($shape['timestampFormat'])
  89. ? $shape['timestampFormat']
  90. : 'unixTimestamp';
  91. return TimestampShape::format($value, $timestampFormat);
  92. default:
  93. return $value;
  94. }
  95. }
  96. }