Passed
Pull Request — master (#150)
by
unknown
06:33
created

DynamoDbModel::updateAsync()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

Changes 0
Metric Value
eloc 1
dl 0
loc 3
ccs 2
cts 2
cp 1
rs 10
c 0
b 0
f 0
cc 1
nc 1
nop 2
crap 1
1
<?php
2
3
namespace BaoPham\DynamoDb;
4
5
use Exception;
6
use DateTime;
7
use Illuminate\Database\Eloquent\Model;
8
9
/**
10
 * Class DynamoDbModel.
11
 */
12
abstract class DynamoDbModel extends Model
13
{
14
    /**
15
     * Always set this to false since DynamoDb does not support incremental Id.
16
     *
17
     * @var bool
18
     */
19
    public $incrementing = false;
20
21
    /**
22
     * @var \BaoPham\DynamoDb\DynamoDbClientInterface
23
     */
24
    protected static $dynamoDb;
25
26
    /**
27
     * @deprecated
28
     * @var \Aws\DynamoDb\Marshaler
29
     */
30
    protected $marshaler;
31
32
    /**
33
     * @deprecated
34
     * @var \BaoPham\DynamoDb\EmptyAttributeFilter
35
     */
36
    protected $attributeFilter;
37
38
    /**
39
     * Indexes.
40
     *   [
41
     *     '<simple_index_name>' => [
42
     *          'hash' => '<index_key>'
43
     *     ],
44
     *     '<composite_index_name>' => [
45
     *          'hash' => '<index_hash_key>',
46
     *          'range' => '<index_range_key>'
47
     *     ],
48
     *   ]
49
     *
50
     * @var array
51
     */
52
    protected $dynamoDbIndexKeys = [];
53
54
    /**
55
     * Array of your composite key.
56
     * ['<hash>', '<range>']
57
     *
58
     * @var array
59
     */
60
    protected $compositeKey = [];
61
62
    /**
63
     * Default Date format
64
     * ISO 8601 Compliant
65
     */
66
    protected $dateFormat = DateTime::ATOM;
67
68
69 127
    public function __construct(array $attributes = [])
70
    {
71 127
        $this->bootIfNotBooted();
72
73 127
        $this->syncOriginal();
74
75 127
        $this->fill($attributes);
76
77 127
        $this->setupDynamoDb();
78 127
    }
79
80
    /**
81
     * Get the DynamoDbClient service that is being used by the models.
82
     *
83
     * @return DynamoDbClientInterface
84
     */
85 3
    public static function getDynamoDbClientService()
86
    {
87 3
        return static::$dynamoDb;
88
    }
89
90
    /**
91
     * Set the DynamoDbClient used by models.
92
     *
93
     * @param DynamoDbClientInterface $dynamoDb
94
     *
95
     * @return void
96
     */
97 142
    public static function setDynamoDbClientService(DynamoDbClientInterface $dynamoDb)
98
    {
99 142
        static::$dynamoDb = $dynamoDb;
100 142
    }
101
102
    /**
103
     * Unset the DynamoDbClient service for models.
104
     *
105
     * @return void
106
     */
107 3
    public static function unsetDynamoDbClientService()
108
    {
109 3
        static::$dynamoDb = null;
110 3
    }
111
112 127
    protected function setupDynamoDb()
113
    {
114 127
        $this->marshaler = static::$dynamoDb->getMarshaler();
115 127
        $this->attributeFilter = static::$dynamoDb->getAttributeFilter();
116 127
    }
117
118 90
    public function newCollection(array $models = [], $index = null)
119
    {
120 90
        return new DynamoDbCollection($models, $index);
121
    }
122
123 8
    public function save(array $options = [])
124
    {
125 8
        $create = !$this->exists;
126
127 8
        if ($this->fireModelEvent('saving') === false) {
128
            return false;
129
        }
130
131 8
        if ($create && $this->fireModelEvent('creating')  === false) {
132
            return false;
133
        }
134
135 8
        if (!$create && $this->fireModelEvent('updating') === false) {
136
            return false;
137
        }
138
139 8
        if ($this->usesTimestamps()) {
140 8
            $this->updateTimestamps();
141
        }
142
143 8
        $saved = $this->newQuery()->save();
144
145 8
        if (!$saved) {
146
            return $saved;
147
        }
148
149 8
        $this->exists = true;
150 8
        $this->wasRecentlyCreated = $create;
151 8
        $this->fireModelEvent($create ? 'created' : 'updated', false);
152
153 8
        $this->finishSave($options);
154
155 8
        return $saved;
156
    }
157
158
    /**
159
     * Saves the model to DynamoDb asynchronously
160
     * And returns a promise
161
     * @param array $options
162
     * @return bool|\GuzzleHttp\Promise\Promise
163
     */
164 6
    public function saveAsync(array $options = [])
165
    {
166 6
        $create = !$this->exists;
167
168 6
        if ($this->fireModelEvent('saving') === false) {
169
            return false;
170
        }
171
172 6
        if ($create && $this->fireModelEvent('creating')  === false) {
173
            return false;
174
        }
175
176 6
        if (!$create && $this->fireModelEvent('updating') === false) {
177
            return false;
178
        }
179
180 6
        if ($this->usesTimestamps()) {
181 6
            $this->updateTimestamps();
182
        }
183
184 6
        $savePromise = $this->newQuery()->saveAsync();
185
186
        $savePromise->then(function ($result) use ($create, $options) {
187 6
            if (array_get($result, '@metadata.statusCode') === 200) {
188 6
                $this->exists = true;
189 6
                $this->wasRecentlyCreated = $create;
190 6
                $this->fireModelEvent($create ? 'created' : 'updated', false);
191
192 6
                $this->finishSave($options);
193
            }
194 6
        });
195
196 6
        return $savePromise;
197
    }
198
199 3
    public function update(array $attributes = [], array $options = [])
200
    {
201 3
        return $this->fill($attributes)->save();
202
    }
203
204 2
    public function updateAsync(array $attributes = [], array $options = [])
0 ignored issues
show
Unused Code introduced by
The parameter $options is not used and could be removed. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-unused  annotation

204
    public function updateAsync(array $attributes = [], /** @scrutinizer ignore-unused */ array $options = [])

This check looks for parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
205
    {
206 2
        return $this->fill($attributes)->saveAsync();
207
    }
208
209
    public static function create(array $attributes = [])
210
    {
211
        $model = new static;
212
213
        $model->fill($attributes)->save();
214
215
        return $model;
216
    }
217
218 2
    public function delete()
219
    {
220 2
        if (is_null($this->getKeyName())) {
0 ignored issues
show
introduced by
The condition is_null($this->getKeyName()) is always false.
Loading history...
221
            throw new Exception('No primary key defined on model.');
222
        }
223
224 2
        if ($this->exists) {
225 2
            if ($this->fireModelEvent('deleting') === false) {
226
                return false;
227
            }
228
229 2
            $this->exists = false;
230
231 2
            $success = $this->newQuery()->delete();
232
233 2
            if ($success) {
234 2
                $this->fireModelEvent('deleted', false);
235
            }
236
237 2
            return $success;
238
        }
239
    }
240
241 2
    public function deleteAsync()
242
    {
243 2
        if (is_null($this->getKeyName())) {
244
            throw new Exception('No primary key defined on model.');
245
        }
246
247 2
        if ($this->exists) {
248 2
            if ($this->fireModelEvent('deleting') === false) {
249
                return false;
250
            }
251
252 2
            $this->exists = false;
253
254 2
            $deletePromise = $this->newQuery()->deleteAsync();
255
256
            $deletePromise->then(function () {
257 2
                $this->fireModelEvent('deleted', false);
258 2
            });
259
260 2
            return $deletePromise;
261
        }
262
    }
263
264 7
    public static function all($columns = [])
265
    {
266 7
        $instance = new static;
267
268 7
        return $instance->newQuery()->get($columns);
269
    }
270
271 2
    public function refresh()
272
    {
273 2
        if (! $this->exists) {
274
            return $this;
275
        }
276
277 2
        $query = $this->newQuery();
278
279 2
        $refreshed = $query->find($this->getKeys());
280
281 2
        $this->setRawAttributes($refreshed->toArray());
282
283 2
        return $this;
284
    }
285
286
    /**
287
     * @return DynamoDbQueryBuilder
288
     */
289 127
    public function newQuery()
290
    {
291 127
        $builder = new DynamoDbQueryBuilder($this);
292
293 127
        foreach ($this->getGlobalScopes() as $identifier => $scope) {
294 7
            $builder->withGlobalScope($identifier, $scope);
295
        }
296
297 127
        return $builder;
298
    }
299
300 110
    public function hasCompositeKey()
301
    {
302 110
        return !empty($this->compositeKey);
303
    }
304
305
    /**
306
     * @deprecated
307
     * @param $item
308
     * @return array
309
     */
310
    public function marshalItem($item)
311
    {
312
        return $this->marshaler->marshalItem($item);
313
    }
314
315
    /**
316
     * @deprecated
317
     * @param $value
318
     * @return array
319
     */
320
    public function marshalValue($value)
321
    {
322
        return $this->marshaler->marshalValue($value);
323
    }
324
325
    /**
326
     * @deprecated
327
     * @param $item
328
     * @return array|\stdClass
329
     */
330
    public function unmarshalItem($item)
331
    {
332
        return $this->marshaler->unmarshalItem($item);
333
    }
334
335 36
    public function setId($id)
336
    {
337 36
        if (!is_array($id)) {
338 14
            $this->setAttribute($this->getKeyName(), $id);
339
340 14
            return $this;
341
        }
342
343 24
        foreach ($id as $keyName => $value) {
344 24
            $this->setAttribute($keyName, $value);
345
        }
346
347 24
        return $this;
348
    }
349
350
    /**
351
     * @return \Aws\DynamoDb\DynamoDbClient
352
     */
353 127
    public function getClient()
354
    {
355 127
        return static::$dynamoDb->getClient($this->connection);
356
    }
357
358
    /**
359
     * Get the value of the model's primary key.
360
     *
361
     * @return mixed
362
     */
363
    public function getKey()
364
    {
365
        return $this->getAttribute($this->getKeyName());
366
    }
367
368
    /**
369
     * Get the value of the model's primary / composite key.
370
     * Use this if you always want the key values in associative array form.
371
     *
372
     * @return array
373
     *
374
     * ['id' => 'foo']
375
     *
376
     * or
377
     *
378
     * ['id' => 'foo', 'id2' => 'bar']
379
     */
380 46
    public function getKeys()
381
    {
382 46
        if ($this->hasCompositeKey()) {
383 22
            $key = [];
384
385 22
            foreach ($this->compositeKey as $name) {
386 22
                $key[$name] = $this->getAttribute($name);
387
            }
388
389 22
            return $key;
390
        }
391
392 24
        $name = $this->getKeyName();
393
394 24
        return [$name => $this->getAttribute($name)];
395
    }
396
397
    /**
398
     * Get the primary key for the model.
399
     *
400
     * @return string
401
     */
402 28
    public function getKeyName()
403
    {
404 28
        return $this->primaryKey;
405
    }
406
407
    /**
408
     * Get the primary/composite key for the model.
409
     *
410
     * @return array
411
     */
412 104
    public function getKeyNames()
413
    {
414 104
        return $this->hasCompositeKey() ? $this->compositeKey : [$this->primaryKey];
415
    }
416
417
    /**
418
     * @return array
419
     */
420 70
    public function getDynamoDbIndexKeys()
421
    {
422 70
        return $this->dynamoDbIndexKeys;
423
    }
424
425
    /**
426
     * @param array $dynamoDbIndexKeys
427
     */
428
    public function setDynamoDbIndexKeys($dynamoDbIndexKeys)
429
    {
430
        $this->dynamoDbIndexKeys = $dynamoDbIndexKeys;
431
    }
432
433
    /**
434
     * @deprecated
435
     * @return \Aws\DynamoDb\Marshaler
436
     */
437
    public function getMarshaler()
438
    {
439
        return $this->marshaler;
440
    }
441
442
    /**
443
     * Remove non-serializable properties when serializing.
444
     *
445
     * @return array
446
     */
447 2
    public function __sleep()
448
    {
449 2
        return array_keys(
450 2
            array_except(get_object_vars($this), ['marshaler', 'attributeFilter'])
451
        );
452
    }
453
454
    /**
455
     * When a model is being unserialized, check if it needs to be booted and setup DynamoDB.
456
     *
457
     * @return void
458
     */
459 2
    public function __wakeup()
460
    {
461 2
        parent::__wakeup();
462 2
        $this->setupDynamoDb();
463 2
    }
464
}
465