summaryrefslogtreecommitdiff
path: root/vendor/aws/aws-sdk-php/src/DynamoDb/Marshaler.php
blob: f86452c6cbdab0724d1fdd5566fb7ab45d9216a3 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
<?php
namespace Aws\DynamoDb;

use Psr\Http\Message\StreamInterface;

/**
 * Marshals and unmarshals JSON documents and PHP arrays into DynamoDB items.
 */
class Marshaler
{
    /** @var array Default options to merge into provided options. */
    private static $defaultOptions = [
        'ignore_invalid'  => false,
        'nullify_invalid' => false,
        'wrap_numbers'    => false,
    ];

    /** @var array Marshaler options. */
    private $options;

    /**
     * Instantiates a DynamoDB Marshaler.
     *
     * The following options are valid.
     *
     * - ignore_invalid: (bool) Set to `true` if invalid values should be
     *   ignored (i.e., not included) during marshaling.
     * - nullify_invalid: (bool) Set to `true` if invalid values should be set
     *   to null.
     * - wrap_numbers: (bool) Set to `true` to wrap numbers with `NumberValue`
     *   objects during unmarshaling to preserve the precision.
     *
     * @param array $options Marshaler options
     */
    public function __construct(array $options = [])
    {
        $this->options = $options + self::$defaultOptions;
    }

    /**
     * Creates a special object to represent a DynamoDB binary (B) value.
     *
     * This helps disambiguate binary values from string (S) values.
     *
     * @param mixed $value A binary value compatible with Guzzle streams.
     *
     * @return BinaryValue
     * @see GuzzleHttp\Stream\Stream::factory
     */
    public function binary($value)
    {
        return new BinaryValue($value);
    }

    /**
     * Creates a special object to represent a DynamoDB number (N) value.
     *
     * This helps maintain the precision of large integer/float in PHP.
     *
     * @param string|int|float $value A number value.
     *
     * @return NumberValue
     */
    public function number($value)
    {
        return new NumberValue($value);
    }

    /**
     * Creates a special object to represent a DynamoDB set (SS/NS/BS) value.
     *
     * This helps disambiguate set values from list (L) values.
     *
     * @param array $values The values of the set.
     *
     * @return SetValue
     *
     */
    public function set(array $values)
    {
        return new SetValue($values);
    }

    /**
     * Marshal a JSON document from a string to a DynamoDB item.
     *
     * The result is an array formatted in the proper parameter structure
     * required by the DynamoDB API for items.
     *
     * @param string $json A valid JSON document.
     *
     * @return array Item formatted for DynamoDB.
     * @throws \InvalidArgumentException if the JSON is invalid.
     */
    public function marshalJson($json)
    {
        $data = json_decode($json);
        if (!($data instanceof \stdClass)) {
            throw new \InvalidArgumentException(
                'The JSON document must be valid and be an object at its root.'
            );
        }

        return current($this->marshalValue($data));
    }

    /**
     * Marshal a native PHP array of data to a DynamoDB item.
     *
     * The result is an array formatted in the proper parameter structure
     * required by the DynamoDB API for items.
     *
     * @param array|\stdClass $item An associative array of data.
     *
     * @return array Item formatted for DynamoDB.
     */
    public function marshalItem($item)
    {
        return current($this->marshalValue($item));
    }

    /**
     * Marshal a native PHP value into a DynamoDB attribute value.
     *
     * The result is an associative array that is formatted in the proper
     * `[TYPE => VALUE]` parameter structure required by the DynamoDB API.
     *
     * @param mixed $value A scalar, array, or `stdClass` value.
     *
     * @return array Attribute formatted for DynamoDB.
     * @throws \UnexpectedValueException if the value cannot be marshaled.
     */
    public function marshalValue($value)
    {
        $type = gettype($value);

        // Handle string values.
        if ($type === 'string') {
            return ['S' => $value];
        }

        // Handle number values.
        if ($type === 'integer'
            || $type === 'double'
            || $value instanceof NumberValue
        ) {
            return ['N' => (string) $value];
        }

        // Handle boolean values.
        if ($type === 'boolean') {
            return ['BOOL' => $value];
        }

        // Handle null values.
        if ($type === 'NULL') {
            return ['NULL' => true];
        }

        // Handle set values.
        if ($value instanceof SetValue) {
            if (count($value) === 0) {
                return $this->handleInvalid('empty sets are invalid');
            }
            $previousType = null;
            $data = [];
            foreach ($value as $v) {
                $marshaled = $this->marshalValue($v);
                $setType = key($marshaled);
                if (!$previousType) {
                    $previousType = $setType;
                } elseif ($setType !== $previousType) {
                    return $this->handleInvalid('sets must be uniform in type');
                }
                $data[] = current($marshaled);
            }

            return [$previousType . 'S' => array_values(array_unique($data))];
        }

        // Handle list and map values.
        $dbType = 'L';
        if ($value instanceof \stdClass) {
            $type = 'array';
            $dbType = 'M';
        }
        if ($type === 'array' || $value instanceof \Traversable) {
            $data = [];
            $index = 0;
            foreach ($value as $k => $v) {
                if ($v = $this->marshalValue($v)) {
                    $data[$k] = $v;
                    if ($dbType === 'L' && (!is_int($k) || $k != $index++)) {
                        $dbType = 'M';
                    }
                }
            }
            return [$dbType => $data];
        }

        // Handle binary values.
        if (is_resource($value) || $value instanceof StreamInterface) {
            $value = $this->binary($value);
        }
        if ($value instanceof BinaryValue) {
            return ['B' => (string) $value];
        }

        // Handle invalid values.
        return $this->handleInvalid('encountered unexpected value');
    }

    /**
     * Unmarshal a document (item) from a DynamoDB operation result into a JSON
     * document string.
     *
     * @param array $data            Item/document from a DynamoDB result.
     * @param int   $jsonEncodeFlags Flags to use with `json_encode()`.
     *
     * @return string
     */
    public function unmarshalJson(array $data, $jsonEncodeFlags = 0)
    {
        return json_encode(
            $this->unmarshalValue(['M' => $data], true),
            $jsonEncodeFlags
        );
    }

    /**
     * Unmarshal an item from a DynamoDB operation result into a native PHP
     * array. If you set $mapAsObject to true, then a stdClass value will be
     * returned instead.
     *
     * @param array $data Item from a DynamoDB result.
     * @param bool  $mapAsObject Whether maps should be represented as stdClass.
     *
     * @return array|\stdClass
     */
    public function unmarshalItem(array $data, $mapAsObject = false)
    {
        return $this->unmarshalValue(['M' => $data], $mapAsObject);
    }

    /**
     * Unmarshal a value from a DynamoDB operation result into a native PHP
     * value. Will return a scalar, array, or (if you set $mapAsObject to true)
     * stdClass value.
     *
     * @param array $value       Value from a DynamoDB result.
     * @param bool  $mapAsObject Whether maps should be represented as stdClass.
     *
     * @return mixed
     * @throws \UnexpectedValueException
     */
    public function unmarshalValue(array $value, $mapAsObject = false)
    {
        $type = key($value);
        $value = $value[$type];
        switch ($type) {
            case 'S':
            case 'BOOL':
                return $value;
            case 'NULL':
                return null;
            case 'N':
                if ($this->options['wrap_numbers']) {
                    return new NumberValue($value);
                }

                // Use type coercion to unmarshal numbers to int/float.
                return $value + 0;
            case 'M':
                if ($mapAsObject) {
                    $data = new \stdClass;
                    foreach ($value as $k => $v) {
                        $data->$k = $this->unmarshalValue($v, $mapAsObject);
                    }
                    return $data;
                }
                // NOBREAK: Unmarshal M the same way as L, for arrays.
            case 'L':
                foreach ($value as $k => $v) {
                    $value[$k] = $this->unmarshalValue($v, $mapAsObject);
                }
                return $value;
            case 'B':
                return new BinaryValue($value);
            case 'SS':
            case 'NS':
            case 'BS':
                foreach ($value as $k => $v) {
                    $value[$k] = $this->unmarshalValue([$type[0] => $v]);
                }
                return new SetValue($value);
        }

        throw new \UnexpectedValueException("Unexpected type: {$type}.");
    }

    /**
     * Handle invalid value based on marshaler configuration.
     *
     * @param string $message Error message
     *
     * @return array|null
     */
    private function handleInvalid($message)
    {
        if ($this->options['ignore_invalid']) {
            return null;
        }

        if ($this->options['nullify_invalid']) {
            return ['NULL' => true];
        }

        throw new \UnexpectedValueException("Marshaling error: {$message}.");
    }
}