Completed
Pull Request — master (#150)
by
unknown
07:21
created

DynamoDbModel   C

Complexity

Total Complexity 56

Size/Duplication

Total Lines 417
Duplicated Lines 0 %

Test Coverage

Coverage 78.2%

Importance

Changes 0
Metric Value
wmc 56
eloc 106
dl 0
loc 417
ccs 104
cts 133
cp 0.782
rs 5.5199
c 0
b 0
f 0

29 Methods

Rating   Name   Duplication   Size   Complexity  
A getDynamoDbClientService() 0 3 1
A unsetDynamoDbClientService() 0 3 1
A setupDynamoDb() 0 4 1
A __construct() 0 9 1
A newCollection() 0 3 1
A setDynamoDbClientService() 0 3 1
B save() 0 33 9
A getKeyNames() 0 3 2
A unmarshalItem() 0 3 1
A marshalValue() 0 3 1
A getMarshaler() 0 3 1
B saveAsync() 0 33 9
A all() 0 5 1
A getKey() 0 3 1
A getDynamoDbIndexKeys() 0 3 1
A hasCompositeKey() 0 3 1
A getKeys() 0 15 3
A update() 0 3 1
A __wakeup() 0 4 1
A refresh() 0 13 2
A newQuery() 0 9 2
A getKeyName() 0 3 1
A setDynamoDbIndexKeys() 0 3 1
A delete() 0 20 5
A create() 0 7 1
A getClient() 0 3 1
A setId() 0 13 3
A marshalItem() 0 3 1
A __sleep() 0 4 1

How to fix   Complexity   

Complex Class

Complex classes like DynamoDbModel often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

While breaking up the class, it is a good idea to analyze how other classes use DynamoDbModel, and based on these observations, apply Extract Interface, too.

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 123
    public function __construct(array $attributes = [])
70
    {
71 123
        $this->bootIfNotBooted();
72
73 123
        $this->syncOriginal();
74
75 123
        $this->fill($attributes);
76
77 123
        $this->setupDynamoDb();
78 123
    }
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 138
    public static function setDynamoDbClientService(DynamoDbClientInterface $dynamoDb)
98
    {
99 138
        static::$dynamoDb = $dynamoDb;
100 138
    }
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 123
    protected function setupDynamoDb()
113
    {
114 123
        $this->marshaler = static::$dynamoDb->getMarshaler();
115 123
        $this->attributeFilter = static::$dynamoDb->getAttributeFilter();
116 123
    }
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 4
    public function saveAsync(array $options = [])
159
    {
160 4
        $create = !$this->exists;
161
162 4
        if ($this->fireModelEvent('saving') === false) {
163
            return false;
164
        }
165
166 4
        if ($create && $this->fireModelEvent('creating')  === false) {
167
            return false;
168
        }
169
170 4
        if (!$create && $this->fireModelEvent('updating') === false) {
171
            return false;
172
        }
173
174 4
        if ($this->usesTimestamps()) {
175 4
            $this->updateTimestamps();
176
        }
177
178 4
        $savePromise = $this->newQuery()->saveAsync();
179
180 4
        if (!$savePromise) {
0 ignored issues
show
introduced by
$savePromise is of type GuzzleHttp\Promise\Promise, thus it always evaluated to true.
Loading history...
181
            return $savePromise;
182
        }
183
184 4
        $this->exists = true;
185 4
        $this->wasRecentlyCreated = $create;
186 4
        $this->fireModelEvent($create ? 'created' : 'updated', false);
187
188 4
        $this->finishSave($options);
189
190 4
        return $savePromise;
191
    }
192
193 3
    public function update(array $attributes = [], array $options = [])
194
    {
195 3
        return $this->fill($attributes)->save();
196
    }
197
198
    public static function create(array $attributes = [])
199
    {
200
        $model = new static;
201
202
        $model->fill($attributes)->save();
203
204
        return $model;
205
    }
206
207 2
    public function delete()
208
    {
209 2
        if (is_null($this->getKeyName())) {
210
            throw new Exception('No primary key defined on model.');
211
        }
212
213 2
        if ($this->exists) {
214 2
            if ($this->fireModelEvent('deleting') === false) {
215
                return false;
216
            }
217
218 2
            $this->exists = false;
219
220 2
            $success = $this->newQuery()->delete();
221
222 2
            if ($success) {
223 2
                $this->fireModelEvent('deleted', false);
224
            }
225
226 2
            return $success;
227
        }
228
    }
229
230 7
    public static function all($columns = [])
231
    {
232 7
        $instance = new static;
233
234 7
        return $instance->newQuery()->get($columns);
235
    }
236
237 2
    public function refresh()
238
    {
239 2
        if (! $this->exists) {
240
            return $this;
241
        }
242
243 2
        $query = $this->newQuery();
244
245 2
        $refreshed = $query->find($this->getKeys());
246
247 2
        $this->setRawAttributes($refreshed->toArray());
248
249 2
        return $this;
250
    }
251
252
    /**
253
     * @return DynamoDbQueryBuilder
254
     */
255 123
    public function newQuery()
256
    {
257 123
        $builder = new DynamoDbQueryBuilder($this);
258
259 123
        foreach ($this->getGlobalScopes() as $identifier => $scope) {
260 7
            $builder->withGlobalScope($identifier, $scope);
261
        }
262
263 123
        return $builder;
264
    }
265
266 106
    public function hasCompositeKey()
267
    {
268 106
        return !empty($this->compositeKey);
269
    }
270
271
    /**
272
     * @deprecated
273
     * @param $item
274
     * @return array
275
     */
276
    public function marshalItem($item)
277
    {
278
        return $this->marshaler->marshalItem($item);
279
    }
280
281
    /**
282
     * @deprecated
283
     * @param $value
284
     * @return array
285
     */
286
    public function marshalValue($value)
287
    {
288
        return $this->marshaler->marshalValue($value);
289
    }
290
291
    /**
292
     * @deprecated
293
     * @param $item
294
     * @return array|\stdClass
295
     */
296
    public function unmarshalItem($item)
297
    {
298
        return $this->marshaler->unmarshalItem($item);
299
    }
300
301 32
    public function setId($id)
302
    {
303 32
        if (!is_array($id)) {
304 12
            $this->setAttribute($this->getKeyName(), $id);
305
306 12
            return $this;
307
        }
308
309 22
        foreach ($id as $keyName => $value) {
310 22
            $this->setAttribute($keyName, $value);
311
        }
312
313 22
        return $this;
314
    }
315
316
    /**
317
     * @return \Aws\DynamoDb\DynamoDbClient
318
     */
319 123
    public function getClient()
320
    {
321 123
        return static::$dynamoDb->getClient($this->connection);
322
    }
323
324
    /**
325
     * Get the value of the model's primary key.
326
     *
327
     * @return mixed
328
     */
329
    public function getKey()
330
    {
331
        return $this->getAttribute($this->getKeyName());
332
    }
333
334
    /**
335
     * Get the value of the model's primary / composite key.
336
     * Use this if you always want the key values in associative array form.
337
     *
338
     * @return array
339
     *
340
     * ['id' => 'foo']
341
     *
342
     * or
343
     *
344
     * ['id' => 'foo', 'id2' => 'bar']
345
     */
346 42
    public function getKeys()
347
    {
348 42
        if ($this->hasCompositeKey()) {
349 20
            $key = [];
350
351 20
            foreach ($this->compositeKey as $name) {
352 20
                $key[$name] = $this->getAttribute($name);
353
            }
354
355 20
            return $key;
356
        }
357
358 22
        $name = $this->getKeyName();
359
360 22
        return [$name => $this->getAttribute($name)];
361
    }
362
363
    /**
364
     * Get the primary key for the model.
365
     *
366
     * @return string
367
     */
368 25
    public function getKeyName()
369
    {
370 25
        return $this->primaryKey;
371
    }
372
373
    /**
374
     * Get the primary/composite key for the model.
375
     *
376
     * @return array
377
     */
378 100
    public function getKeyNames()
379
    {
380 100
        return $this->hasCompositeKey() ? $this->compositeKey : [$this->primaryKey];
381
    }
382
383
    /**
384
     * @return array
385
     */
386 70
    public function getDynamoDbIndexKeys()
387
    {
388 70
        return $this->dynamoDbIndexKeys;
389
    }
390
391
    /**
392
     * @param array $dynamoDbIndexKeys
393
     */
394
    public function setDynamoDbIndexKeys($dynamoDbIndexKeys)
395
    {
396
        $this->dynamoDbIndexKeys = $dynamoDbIndexKeys;
397
    }
398
399
    /**
400
     * @deprecated
401
     * @return \Aws\DynamoDb\Marshaler
402
     */
403
    public function getMarshaler()
404
    {
405
        return $this->marshaler;
406
    }
407
408
    /**
409
     * Remove non-serializable properties when serializing.
410
     *
411
     * @return array
412
     */
413 2
    public function __sleep()
414
    {
415 2
        return array_keys(
416 2
            array_except(get_object_vars($this), ['marshaler', 'attributeFilter'])
417
        );
418
    }
419
420
    /**
421
     * When a model is being unserialized, check if it needs to be booted and setup DynamoDB.
422
     *
423
     * @return void
424
     */
425 2
    public function __wakeup()
426
    {
427 2
        parent::__wakeup();
428 2
        $this->setupDynamoDb();
429 2
    }
430
}
431