Passed
Pull Request — master (#128)
by Bao
07:18
created

DynamoDbModel::newCollection()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

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