Marshaler.php 9.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321
  1. <?php
  2. namespace Aws\DynamoDb;
  3. use Psr\Http\Message\StreamInterface;
  4. /**
  5. * Marshals and unmarshals JSON documents and PHP arrays into DynamoDB items.
  6. */
  7. class Marshaler
  8. {
  9. /** @var array Default options to merge into provided options. */
  10. private static $defaultOptions = [
  11. 'ignore_invalid' => false,
  12. 'nullify_invalid' => false,
  13. 'wrap_numbers' => false,
  14. ];
  15. /** @var array Marshaler options. */
  16. private $options;
  17. /**
  18. * Instantiates a DynamoDB Marshaler.
  19. *
  20. * The following options are valid.
  21. *
  22. * - ignore_invalid: (bool) Set to `true` if invalid values should be
  23. * ignored (i.e., not included) during marshaling.
  24. * - nullify_invalid: (bool) Set to `true` if invalid values should be set
  25. * to null.
  26. * - wrap_numbers: (bool) Set to `true` to wrap numbers with `NumberValue`
  27. * objects during unmarshaling to preserve the precision.
  28. *
  29. * @param array $options Marshaler options
  30. */
  31. public function __construct(array $options = [])
  32. {
  33. $this->options = $options + self::$defaultOptions;
  34. }
  35. /**
  36. * Creates a special object to represent a DynamoDB binary (B) value.
  37. *
  38. * This helps disambiguate binary values from string (S) values.
  39. *
  40. * @param mixed $value A binary value compatible with Guzzle streams.
  41. *
  42. * @return BinaryValue
  43. * @see GuzzleHttp\Stream\Stream::factory
  44. */
  45. public function binary($value)
  46. {
  47. return new BinaryValue($value);
  48. }
  49. /**
  50. * Creates a special object to represent a DynamoDB number (N) value.
  51. *
  52. * This helps maintain the precision of large integer/float in PHP.
  53. *
  54. * @param string|int|float $value A number value.
  55. *
  56. * @return NumberValue
  57. */
  58. public function number($value)
  59. {
  60. return new NumberValue($value);
  61. }
  62. /**
  63. * Creates a special object to represent a DynamoDB set (SS/NS/BS) value.
  64. *
  65. * This helps disambiguate set values from list (L) values.
  66. *
  67. * @param array $values The values of the set.
  68. *
  69. * @return SetValue
  70. *
  71. */
  72. public function set(array $values)
  73. {
  74. return new SetValue($values);
  75. }
  76. /**
  77. * Marshal a JSON document from a string to a DynamoDB item.
  78. *
  79. * The result is an array formatted in the proper parameter structure
  80. * required by the DynamoDB API for items.
  81. *
  82. * @param string $json A valid JSON document.
  83. *
  84. * @return array Item formatted for DynamoDB.
  85. * @throws \InvalidArgumentException if the JSON is invalid.
  86. */
  87. public function marshalJson($json)
  88. {
  89. $data = json_decode($json);
  90. if (!($data instanceof \stdClass)) {
  91. throw new \InvalidArgumentException(
  92. 'The JSON document must be valid and be an object at its root.'
  93. );
  94. }
  95. return current($this->marshalValue($data));
  96. }
  97. /**
  98. * Marshal a native PHP array of data to a DynamoDB item.
  99. *
  100. * The result is an array formatted in the proper parameter structure
  101. * required by the DynamoDB API for items.
  102. *
  103. * @param array|\stdClass $item An associative array of data.
  104. *
  105. * @return array Item formatted for DynamoDB.
  106. */
  107. public function marshalItem($item)
  108. {
  109. return current($this->marshalValue($item));
  110. }
  111. /**
  112. * Marshal a native PHP value into a DynamoDB attribute value.
  113. *
  114. * The result is an associative array that is formatted in the proper
  115. * `[TYPE => VALUE]` parameter structure required by the DynamoDB API.
  116. *
  117. * @param mixed $value A scalar, array, or `stdClass` value.
  118. *
  119. * @return array Attribute formatted for DynamoDB.
  120. * @throws \UnexpectedValueException if the value cannot be marshaled.
  121. */
  122. public function marshalValue($value)
  123. {
  124. $type = gettype($value);
  125. // Handle string values.
  126. if ($type === 'string') {
  127. if ($value === '') {
  128. return $this->handleInvalid('empty strings are invalid');
  129. }
  130. return ['S' => $value];
  131. }
  132. // Handle number values.
  133. if ($type === 'integer'
  134. || $type === 'double'
  135. || $value instanceof NumberValue
  136. ) {
  137. return ['N' => (string) $value];
  138. }
  139. // Handle boolean values.
  140. if ($type === 'boolean') {
  141. return ['BOOL' => $value];
  142. }
  143. // Handle null values.
  144. if ($type === 'NULL') {
  145. return ['NULL' => true];
  146. }
  147. // Handle set values.
  148. if ($value instanceof SetValue) {
  149. if (count($value) === 0) {
  150. return $this->handleInvalid('empty sets are invalid');
  151. }
  152. $previousType = null;
  153. $data = [];
  154. foreach ($value as $v) {
  155. $marshaled = $this->marshalValue($v);
  156. $setType = key($marshaled);
  157. if (!$previousType) {
  158. $previousType = $setType;
  159. } elseif ($setType !== $previousType) {
  160. return $this->handleInvalid('sets must be uniform in type');
  161. }
  162. $data[] = current($marshaled);
  163. }
  164. return [$previousType . 'S' => array_values(array_unique($data))];
  165. }
  166. // Handle list and map values.
  167. $dbType = 'L';
  168. if ($value instanceof \stdClass) {
  169. $type = 'array';
  170. $dbType = 'M';
  171. }
  172. if ($type === 'array' || $value instanceof \Traversable) {
  173. $data = [];
  174. $index = 0;
  175. foreach ($value as $k => $v) {
  176. if ($v = $this->marshalValue($v)) {
  177. $data[$k] = $v;
  178. if ($dbType === 'L' && (!is_int($k) || $k != $index++)) {
  179. $dbType = 'M';
  180. }
  181. }
  182. }
  183. return [$dbType => $data];
  184. }
  185. // Handle binary values.
  186. if (is_resource($value) || $value instanceof StreamInterface) {
  187. $value = $this->binary($value);
  188. }
  189. if ($value instanceof BinaryValue) {
  190. return ['B' => (string) $value];
  191. }
  192. // Handle invalid values.
  193. return $this->handleInvalid('encountered unexpected value');
  194. }
  195. /**
  196. * Unmarshal a document (item) from a DynamoDB operation result into a JSON
  197. * document string.
  198. *
  199. * @param array $data Item/document from a DynamoDB result.
  200. * @param int $jsonEncodeFlags Flags to use with `json_encode()`.
  201. *
  202. * @return string
  203. */
  204. public function unmarshalJson(array $data, $jsonEncodeFlags = 0)
  205. {
  206. return json_encode(
  207. $this->unmarshalValue(['M' => $data], true),
  208. $jsonEncodeFlags
  209. );
  210. }
  211. /**
  212. * Unmarshal an item from a DynamoDB operation result into a native PHP
  213. * array. If you set $mapAsObject to true, then a stdClass value will be
  214. * returned instead.
  215. *
  216. * @param array $data Item from a DynamoDB result.
  217. * @param bool $mapAsObject Whether maps should be represented as stdClass.
  218. *
  219. * @return array|\stdClass
  220. */
  221. public function unmarshalItem(array $data, $mapAsObject = false)
  222. {
  223. return $this->unmarshalValue(['M' => $data], $mapAsObject);
  224. }
  225. /**
  226. * Unmarshal a value from a DynamoDB operation result into a native PHP
  227. * value. Will return a scalar, array, or (if you set $mapAsObject to true)
  228. * stdClass value.
  229. *
  230. * @param array $value Value from a DynamoDB result.
  231. * @param bool $mapAsObject Whether maps should be represented as stdClass.
  232. *
  233. * @return mixed
  234. * @throws \UnexpectedValueException
  235. */
  236. public function unmarshalValue(array $value, $mapAsObject = false)
  237. {
  238. list($type, $value) = each($value);
  239. switch ($type) {
  240. case 'S':
  241. case 'BOOL':
  242. return $value;
  243. case 'NULL':
  244. return null;
  245. case 'N':
  246. if ($this->options['wrap_numbers']) {
  247. return new NumberValue($value);
  248. } else {
  249. // Use type coercion to unmarshal numbers to int/float.
  250. return $value + 0;
  251. }
  252. case 'M':
  253. if ($mapAsObject) {
  254. $data = new \stdClass;
  255. foreach ($value as $k => $v) {
  256. $data->$k = $this->unmarshalValue($v, $mapAsObject);
  257. }
  258. return $data;
  259. }
  260. // NOBREAK: Unmarshal M the same way as L, for arrays.
  261. case 'L':
  262. foreach ($value as $k => $v) {
  263. $value[$k] = $this->unmarshalValue($v, $mapAsObject);
  264. }
  265. return $value;
  266. case 'B':
  267. return new BinaryValue($value);
  268. case 'SS':
  269. case 'NS':
  270. case 'BS':
  271. foreach ($value as $k => $v) {
  272. $value[$k] = $this->unmarshalValue([$type[0] => $v]);
  273. }
  274. return new SetValue($value);
  275. }
  276. throw new \UnexpectedValueException("Unexpected type: {$type}.");
  277. }
  278. /**
  279. * Handle invalid value based on marshaler configuration.
  280. *
  281. * @param string $message Error message
  282. *
  283. * @return array|null
  284. */
  285. private function handleInvalid($message)
  286. {
  287. if ($this->options['ignore_invalid']) {
  288. return null;
  289. } elseif ($this->options['nullify_invalid']) {
  290. return ['NULL' => true];
  291. }
  292. throw new \UnexpectedValueException("Marshaling error: {$message}.");
  293. }
  294. }