Completed
Pull Request — master (#150)
by
unknown
08:29
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
259 2
            });
260
261 2
            return $deletePromise;
262
        }
263
    }
264
265 7
    public static function all($columns = [])
266
    {
267 7
        $instance = new static;
268
269 7
        return $instance->newQuery()->get($columns);
270
    }
271
272 2
    public function refresh()
273
    {
274 2
        if (! $this->exists) {
275
            return $this;
276
        }
277
278 2
        $query = $this->newQuery();
279
280 2
        $refreshed = $query->find($this->getKeys());
281
282 2
        $this->setRawAttributes($refreshed->toArray());
283
284 2
        return $this;
285
    }
286
287
    /**
288
     * @return DynamoDbQueryBuilder
289
     */
290 127
    public function newQuery()
291
    {
292 127
        $builder = new DynamoDbQueryBuilder($this);
293
294 127
        foreach ($this->getGlobalScopes() as $identifier => $scope) {
295 7
            $builder->withGlobalScope($identifier, $scope);
296
        }
297
298 127
        return $builder;
299
    }
300
301 110
    public function hasCompositeKey()
302
    {
303 110
        return !empty($this->compositeKey);
304
    }
305
306
    /**
307
     * @deprecated
308
     * @param $item
309
     * @return array
310
     */
311
    public function marshalItem($item)
312
    {
313
        return $this->marshaler->marshalItem($item);
314
    }
315
316
    /**
317
     * @deprecated
318
     * @param $value
319
     * @return array
320
     */
321
    public function marshalValue($value)
322
    {
323
        return $this->marshaler->marshalValue($value);
324
    }
325
326
    /**
327
     * @deprecated
328
     * @param $item
329
     * @return array|\stdClass
330
     */
331
    public function unmarshalItem($item)
332
    {
333
        return $this->marshaler->unmarshalItem($item);
334
    }
335
336 36
    public function setId($id)
337
    {
338 36
        if (!is_array($id)) {
339 14
            $this->setAttribute($this->getKeyName(), $id);
340
341 14
            return $this;
342
        }
343
344 24
        foreach ($id as $keyName => $value) {
345 24
            $this->setAttribute($keyName, $value);
346
        }
347
348 24
        return $this;
349
    }
350
351
    /**
352
     * @return \Aws\DynamoDb\DynamoDbClient
353
     */
354 127
    public function getClient()
355
    {
356 127
        return static::$dynamoDb->getClient($this->connection);
357
    }
358
359
    /**
360
     * Get the value of the model's primary key.
361
     *
362
     * @return mixed
363
     */
364
    public function getKey()
365
    {
366
        return $this->getAttribute($this->getKeyName());
367
    }
368
369
    /**
370
     * Get the value of the model's primary / composite key.
371
     * Use this if you always want the key values in associative array form.
372
     *
373
     * @return array
374
     *
375
     * ['id' => 'foo']
376
     *
377
     * or
378
     *
379
     * ['id' => 'foo', 'id2' => 'bar']
380
     */
381 46
    public function getKeys()
382
    {
383 46
        if ($this->hasCompositeKey()) {
384 22
            $key = [];
385
386 22
            foreach ($this->compositeKey as $name) {
387 22
                $key[$name] = $this->getAttribute($name);
388
            }
389
390 22
            return $key;
391
        }
392
393 24
        $name = $this->getKeyName();
394
395 24
        return [$name => $this->getAttribute($name)];
396
    }
397
398
    /**
399
     * Get the primary key for the model.
400
     *
401
     * @return string
402
     */
403 28
    public function getKeyName()
404
    {
405 28
        return $this->primaryKey;
406
    }
407
408
    /**
409
     * Get the primary/composite key for the model.
410
     *
411
     * @return array
412
     */
413 104
    public function getKeyNames()
414
    {
415 104
        return $this->hasCompositeKey() ? $this->compositeKey : [$this->primaryKey];
416
    }
417
418
    /**
419
     * @return array
420
     */
421 70
    public function getDynamoDbIndexKeys()
422
    {
423 70
        return $this->dynamoDbIndexKeys;
424
    }
425
426
    /**
427
     * @param array $dynamoDbIndexKeys
428
     */
429
    public function setDynamoDbIndexKeys($dynamoDbIndexKeys)
430
    {
431
        $this->dynamoDbIndexKeys = $dynamoDbIndexKeys;
432
    }
433
434
    /**
435
     * @deprecated
436
     * @return \Aws\DynamoDb\Marshaler
437
     */
438
    public function getMarshaler()
439
    {
440
        return $this->marshaler;
441
    }
442
443
    /**
444
     * Remove non-serializable properties when serializing.
445
     *
446
     * @return array
447
     */
448 2
    public function __sleep()
449
    {
450 2
        return array_keys(
451 2
            array_except(get_object_vars($this), ['marshaler', 'attributeFilter'])
452
        );
453
    }
454
455
    /**
456
     * When a model is being unserialized, check if it needs to be booted and setup DynamoDB.
457
     *
458
     * @return void
459
     */
460 2
    public function __wakeup()
461
    {
462 2
        parent::__wakeup();
463 2
        $this->setupDynamoDb();
464 2
    }
465
}
466