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

DynamoDbModel   C

Complexity

Total Complexity 55

Size/Duplication

Total Lines 413
Duplicated Lines 0 %

Test Coverage

Coverage 78.63%

Importance

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