JsonBody.php 2.5 KB

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