Debian Codegraph @

lib/3rdParty/composer/aws/aws-sdk-php/src/Api/Serializer/JsonBody.php

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