Passed
Push — master ( 1a63d3...1ce1e4 )
by Bao
07:40
created

DynamoDbQueryBuilder::chunk()   A

Complexity

Conditions 4
Paths 5

Size

Total Lines 11
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 7
CRAP Score 4

Importance

Changes 0
Metric Value
eloc 6
dl 0
loc 11
c 0
b 0
f 0
ccs 7
cts 7
cp 1
rs 10
cc 4
nc 5
nop 2
crap 4
1
<?php
2
3
namespace BaoPham\DynamoDb;
4
5
use BaoPham\DynamoDb\Concerns\HasParsers;
6
use BaoPham\DynamoDb\ConditionAnalyzer\Analyzer;
7
use BaoPham\DynamoDb\Facades\DynamoDb;
8
use Closure;
9
use Illuminate\Contracts\Support\Arrayable;
10
use Illuminate\Database\Eloquent\ModelNotFoundException;
11
use Illuminate\Database\Eloquent\Scope;
12
13
class DynamoDbQueryBuilder
14
{
15
    use HasParsers;
16
17
    const MAX_LIMIT = -1;
18
    const DEFAULT_TO_ITERATOR = true;
19
20
    /**
21
     * The maximum number of records to return.
22
     *
23
     * @var int
24
     */
25
    public $limit;
26
27
    /**
28
     * @var array
29
     */
30
    public $wheres = [];
31
32
    /**
33
     * @var DynamoDbModel
34
     */
35
    protected $model;
36
37
    /**
38
     * @var \Aws\DynamoDb\DynamoDbClient
39
     */
40
    protected $client;
41
42
    /**
43
     * @var Closure
44
     */
45
    protected $decorator;
46
47
    /**
48
     * Applied global scopes.
49
     *
50
     * @var array
51
     */
52
    protected $scopes = [];
53
54
    /**
55
     * Removed global scopes.
56
     *
57
     * @var array
58
     */
59
    protected $removedScopes = [];
60
61
    /**
62
     * When not using the iterator, you can store the lastEvaluatedKey to
63
     * paginate through the results. The getAll method will take this into account
64
     * when used with $use_iterator = false.
65
     *
66
     * @var mixed
67
     */
68
    protected $lastEvaluatedKey;
69
70
    /**
71
     * Specified index name for the query.
72
     *
73
     * @var string
74
     */
75
    protected $index;
76
77 119
    public function __construct(DynamoDbModel $model)
78
    {
79 119
        $this->model = $model;
80 119
        $this->client = $model->getClient();
81 119
        $this->setupExpressions();
82 119
    }
83
84
    /**
85
     * Alias to set the "limit" value of the query.
86
     *
87
     * @param  int  $value
88
     * @return DynamoDbQueryBuilder
89
     */
90 6
    public function take($value)
91
    {
92 6
        return $this->limit($value);
93
    }
94
95
    /**
96
     * Set the "limit" value of the query.
97
     *
98
     * @param  int  $value
99
     * @return $this
100
     */
101 14
    public function limit($value)
102
    {
103 14
        $this->limit = $value;
104
105 14
        return $this;
106
    }
107
108
    /**
109
     * Alias to set the "offset" value of the query.
110
     *
111
     * @param  int $value
112
     * @throws NotSupportedException
113
     */
114
    public function skip($value)
115
    {
116
        return $this->offset($value);
117
    }
118
119
    /**
120
     * Set the "offset" value of the query.
121
     *
122
     * @param  int $value
123
     * @throws NotSupportedException
124
     */
125
    public function offset($value)
126
    {
127
        throw new NotSupportedException('Skip/Offset is not supported. Consider using after() instead');
128
    }
129
130
    /**
131
     * Determine the starting point (exclusively) of the query.
132
     * Unfortunately, offset of how many records to skip does not make sense for DynamoDb.
133
     * Instead, provide the last result of the previous query as the starting point for the next query.
134
     *
135
     * @param  DynamoDbModel|null  $after
136
     *   Examples:
137
     *
138
     *   For query such as
139
     *       $query = $model->where('count', 10)->limit(2);
140
     *       $last = $query->all()->last();
141
     *   Take the last item of this query result as the next "offset":
142
     *       $nextPage = $query->after($last)->limit(2)->all();
143
     *
144
     *   Alternatively, pass in nothing to reset the starting point.
145
     *
146
     * @return $this
147
     */
148 4
    public function after(DynamoDbModel $after = null)
149
    {
150 4
        if (empty($after)) {
151 4
            $this->lastEvaluatedKey = null;
152
153 4
            return $this;
154
        }
155
156 4
        $afterKey = $after->getKeys();
157
158 4
        $analyzer = $this->getConditionAnalyzer();
159
160 4
        if ($index = $analyzer->index()) {
161 1
            foreach ($index->columns() as $column) {
162 1
                $afterKey[$column] = $after->getAttribute($column);
163
            }
164
        }
165
166 4
        $this->lastEvaluatedKey = DynamoDb::marshalItem($afterKey);
167
168 4
        return $this;
169
    }
170
171
    /**
172
     * Similar to after(), but instead of using the model instance, the model's keys are used.
173
     * Use $collection->lastKey() or $model->getKeys() to retrieve the value.
174
     *
175
     * @param  Array  $key
176
     *   Examples:
177
     *
178
     *   For query such as
179
     *       $query = $model->where('count', 10)->limit(2);
180
     *       $items = $query->all();
181
     *   Take the last item of this query result as the next "offset":
182
     *       $nextPage = $query->afterKey($items->lastKey())->limit(2)->all();
183
     *
184
     *   Alternatively, pass in nothing to reset the starting point.
185
     *
186
     * @return $this
187
     */
188 4
    public function afterKey($key = null)
189
    {
190 4
        $this->lastEvaluatedKey = empty($key) ? null : DynamoDb::marshalItem($key);
191 4
        return $this;
192
    }
193
194
    /**
195
     * Set the index name manually
196
     *
197
     * @param string $index The index name
198
     * @return $this
199
     */
200 1
    public function withIndex($index)
201
    {
202 1
        $this->index = $index;
203 1
        return $this;
204
    }
205
206 74
    public function where($column, $operator = null, $value = null, $boolean = 'and')
207
    {
208
        // If the column is an array, we will assume it is an array of key-value pairs
209
        // and can add them each as a where clause. We will maintain the boolean we
210
        // received when the method was called and pass it into the nested where.
211 74
        if (is_array($column)) {
212
            foreach ($column as $key => $value) {
213
                return $this->where($key, '=', $value);
214
            }
215
        }
216
217
        // Here we will make some assumptions about the operator. If only 2 values are
218
        // passed to the method, we will assume that the operator is an equals sign
219
        // and keep going. Otherwise, we'll require the operator to be passed in.
220 74
        if (func_num_args() == 2) {
221 45
            list($value, $operator) = [$operator, '='];
222
        }
223
224
        // If the columns is actually a Closure instance, we will assume the developer
225
        // wants to begin a nested where statement which is wrapped in parenthesis.
226
        // We'll add that Closure to the query then return back out immediately.
227 74
        if ($column instanceof Closure) {
228 2
            return $this->whereNested($column, $boolean);
229
        }
230
231
        // If the given operator is not found in the list of valid operators we will
232
        // assume that the developer is just short-cutting the '=' operators and
233
        // we will set the operators to '=' and set the values appropriately.
234 74
        if (!ComparisonOperator::isValidOperator($operator)) {
235 4
            list($value, $operator) = [$operator, '='];
236
        }
237
238
        // If the value is a Closure, it means the developer is performing an entire
239
        // sub-select within the query and we will need to compile the sub-select
240
        // within the where clause to get the appropriate query record results.
241 74
        if ($value instanceof Closure) {
242
            throw new NotSupportedException('Closure in where clause is not supported');
243
        }
244
245 74
        $this->wheres[] = [
246 74
            'column' => $column,
247 74
            'type' => ComparisonOperator::getDynamoDbOperator($operator),
248 74
            'value' => $value,
249 74
            'boolean' => $boolean,
250
        ];
251
252 74
        return $this;
253
    }
254
255
    /**
256
     * Add a nested where statement to the query.
257
     *
258
     * @param  \Closure $callback
259
     * @param  string   $boolean
260
     * @return $this
261
     */
262 2
    public function whereNested(Closure $callback, $boolean = 'and')
263
    {
264 2
        call_user_func($callback, $query = $this->forNestedWhere());
265
266 2
        return $this->addNestedWhereQuery($query, $boolean);
267
    }
268
269
    /**
270
     * Create a new query instance for nested where condition.
271
     *
272
     * @return $this
273
     */
274 2
    public function forNestedWhere()
275
    {
276 2
        return $this->newQuery();
277
    }
278
279
    /**
280
     * Add another query builder as a nested where to the query builder.
281
     *
282
     * @param  DynamoDbQueryBuilder $query
283
     * @param  string  $boolean
284
     * @return $this
285
     */
286 2
    public function addNestedWhereQuery($query, $boolean = 'and')
287
    {
288 2
        if (count($query->wheres)) {
289 2
            $type = 'Nested';
290 2
            $column = null;
291 2
            $value = $query->wheres;
292 2
            $this->wheres[] = compact('column', 'type', 'value', 'boolean');
293
        }
294
295 2
        return $this;
296
    }
297
298
    /**
299
     * Add an "or where" clause to the query.
300
     *
301
     * @param  string  $column
302
     * @param  string  $operator
303
     * @param  mixed   $value
304
     * @return $this
305
     */
306 22
    public function orWhere($column, $operator = null, $value = null)
307
    {
308 22
        return $this->where($column, $operator, $value, 'or');
309
    }
310
311
    /**
312
     * Add a "where in" clause to the query.
313
     *
314
     * @param  string  $column
315
     * @param  mixed   $values
316
     * @param  string  $boolean
317
     * @param  bool    $not
318
     * @return $this
319
     * @throws NotSupportedException
320
     */
321 2
    public function whereIn($column, $values, $boolean = 'and', $not = false)
322
    {
323 2
        if ($not) {
324
            throw new NotSupportedException('"not in" is not a valid DynamoDB comparison operator');
325
        }
326
327
        // If the value is a query builder instance, not supported
328 2
        if ($values instanceof static) {
329
            throw new NotSupportedException('Value is a query builder instance');
330
        }
331
332
        // If the value of the where in clause is actually a Closure, not supported
333 2
        if ($values instanceof Closure) {
334
            throw new NotSupportedException('Value is a Closure');
335
        }
336
337
        // Next, if the value is Arrayable we need to cast it to its raw array form
338 2
        if ($values instanceof Arrayable) {
339
            $values = $values->toArray();
340
        }
341
342 2
        return $this->where($column, ComparisonOperator::IN, $values, $boolean);
343
    }
344
345
    /**
346
     * Add an "or where in" clause to the query.
347
     *
348
     * @param  string  $column
349
     * @param  mixed   $values
350
     * @return $this
351
     */
352 2
    public function orWhereIn($column, $values)
353
    {
354 2
        return $this->whereIn($column, $values, 'or');
355
    }
356
357
    /**
358
     * Add a "where null" clause to the query.
359
     *
360
     * @param  string  $column
361
     * @param  string  $boolean
362
     * @param  bool    $not
363
     * @return $this
364
     */
365 4
    public function whereNull($column, $boolean = 'and', $not = false)
366
    {
367 4
        $type = $not ? ComparisonOperator::NOT_NULL : ComparisonOperator::NULL;
368
369 4
        $this->wheres[] = compact('column', 'type', 'boolean');
370
371 4
        return $this;
372
    }
373
374
    /**
375
     * Add an "or where null" clause to the query.
376
     *
377
     * @param  string  $column
378
     * @return $this
379
     */
380 2
    public function orWhereNull($column)
381
    {
382 2
        return $this->whereNull($column, 'or');
383
    }
384
385
    /**
386
     * Add an "or where not null" clause to the query.
387
     *
388
     * @param  string  $column
389
     * @return $this
390
     */
391 2
    public function orWhereNotNull($column)
392
    {
393 2
        return $this->whereNotNull($column, 'or');
394
    }
395
396
    /**
397
     * Add a "where not null" clause to the query.
398
     *
399
     * @param  string  $column
400
     * @param  string  $boolean
401
     * @return $this
402
     */
403 2
    public function whereNotNull($column, $boolean = 'and')
404
    {
405 2
        return $this->whereNull($column, $boolean, true);
406
    }
407
408
    /**
409
     * Get a new instance of the query builder.
410
     *
411
     * @return DynamoDbQueryBuilder
412
     */
413 2
    public function newQuery()
414
    {
415 2
        return new static($this->getModel());
416
    }
417
418
    /**
419
     * Implements the Query Chunk method
420
     *
421
     * @param int $chunkSize
422
     * @param callable $callback
423
     */
424 7
    public function chunk($chunkSize, callable $callback)
425
    {
426 7
        while (true) {
427 7
            $results = $this->getAll([], $chunkSize, false);
428
429 7
            if ($results->isNotEmpty()) {
430 7
                call_user_func($callback, $results);
431
            }
432
433 7
            if (empty($this->lastEvaluatedKey)) {
434 7
                break;
435
            }
436
        }
437 7
    }
438
439
    /**
440
     * @param $id
441
     * @param array $columns
442
     * @return DynamoDbModel|\Illuminate\Database\Eloquent\Collection|null
443
     */
444 34
    public function find($id, array $columns = [])
445
    {
446 34
        if ($this->isMultipleIds($id)) {
447 4
            return $this->findMany($id, $columns);
448
        }
449
450 30
        $this->resetExpressions();
451
452 30
        $this->model->setId($id);
453
454 30
        $query = DynamoDb::table($this->model->getTable())
455 30
            ->setKey(DynamoDb::marshalItem($this->model->getKeys()))
456 30
            ->setConsistentRead(true);
457
458 30
        if (!empty($columns)) {
459
            $query
460 3
                ->setProjectionExpression($this->projectionExpression->parse($columns))
461 3
                ->setExpressionAttributeNames($this->expressionAttributeNames->all());
462
        }
463
464 30
        $item = $query->prepare($this->client)->getItem();
465
466 30
        $item = array_get($item->toArray(), 'Item');
467
468 30
        if (empty($item)) {
469 4
            return null;
470
        }
471
472 26
        $item = DynamoDb::unmarshalItem($item);
473
474 26
        $model = $this->model->newInstance([], true);
475
476 26
        $model->setRawAttributes($item, true);
477
478 26
        return $model;
479
    }
480
481
    /**
482
     * @param $ids
483
     * @param array $columns
484
     * @return \Illuminate\Database\Eloquent\Collection
485
     */
486 4
    public function findMany($ids, array $columns = [])
487
    {
488 4
        $collection = $this->model->newCollection();
489
490 4
        if (empty($ids)) {
491
            return $collection;
492
        }
493
494 4
        $this->resetExpressions();
495
496 4
        $table = $this->model->getTable();
497
498
        $keys = collect($ids)->map(function ($id) {
499 4
            if (! is_array($id)) {
500 2
                $id = [$this->model->getKeyName() => $id];
501
            }
502
503 4
            return DynamoDb::marshalItem($id);
504 4
        });
505
506 4
        $subQuery = DynamoDb::newQuery()
507 4
            ->setKeys($keys->toArray())
508 4
            ->setProjectionExpression($this->projectionExpression->parse($columns))
509 4
            ->setExpressionAttributeNames($this->expressionAttributeNames->all())
510 4
            ->prepare($this->client)
511 4
            ->query;
512
513 4
        $results = DynamoDb::newQuery()
514 4
            ->setRequestItems([$table => $subQuery])
515 4
            ->prepare($this->client)
516 4
            ->batchGetItem();
517
518 4
        foreach ($results['Responses'][$table] as $item) {
519 4
            $item = DynamoDb::unmarshalItem($item);
520 4
            $model = $this->model->newInstance([], true);
521 4
            $model->setRawAttributes($item, true);
522 4
            $collection->add($model);
523
        }
524
525 4
        return $collection;
526
    }
527
528 5
    public function findOrFail($id, $columns = [])
529
    {
530 5
        $result = $this->find($id, $columns);
531
532 5
        if ($this->isMultipleIds($id)) {
533 1
            if (count($result) == count(array_unique($id))) {
534 1
                return $result;
535
            }
536 4
        } elseif (! is_null($result)) {
537 2
            return $result;
538
        }
539
540 2
        throw (new ModelNotFoundException)->setModel(
541 2
            get_class($this->model),
542 2
            $id
543
        );
544
    }
545
546 16
    public function first($columns = [])
547
    {
548 16
        $items = $this->getAll($columns, 1);
549
550 16
        return $items->first();
551
    }
552
553 6
    public function firstOrFail($columns = [])
554
    {
555 6
        if (! is_null($model = $this->first($columns))) {
556 4
            return $model;
557
        }
558
559 2
        throw (new ModelNotFoundException)->setModel(get_class($this->model));
560
    }
561
562
    /**
563
     * Remove attributes from an existing item
564
     *
565
     * @param array ...$attributes
566
     * @return bool
567
     * @throws InvalidQuery
568
     */
569 6
    public function removeAttribute(...$attributes)
570
    {
571 6
        $keySet = !empty(array_filter($this->model->getKeys()));
572
573 6
        if (!$keySet) {
574 4
            $analyzer = $this->getConditionAnalyzer();
575
576 4
            if (!$analyzer->isExactSearch()) {
577
                throw new InvalidQuery('Need to provide the key in your query');
578
            }
579
580 4
            $id = $analyzer->identifierConditionValues();
581 4
            $this->model->setId($id);
582
        }
583
584 6
        $key = DynamoDb::marshalItem($this->model->getKeys());
585
586 6
        $this->resetExpressions();
587
588 6
        $result = DynamoDb::table($this->model->getTable())
589 6
            ->setKey($key)
590 6
            ->setUpdateExpression($this->updateExpression->remove($attributes))
591 6
            ->setExpressionAttributeNames($this->expressionAttributeNames->all())
592 6
            ->prepare($this->client)
593 6
            ->updateItem();
594
595 6
        return array_get($result, '@metadata.statusCode') === 200;
596
    }
597
598 2
    public function delete()
599
    {
600 2
        $result = DynamoDb::table($this->model->getTable())
601 2
            ->setKey(DynamoDb::marshalItem($this->model->getKeys()))
602 2
            ->prepare($this->client)
603 2
            ->deleteItem();
604
605 2
        return array_get($result->toArray(), '@metadata.statusCode') === 200;
606
    }
607
608 8
    public function save()
609
    {
610 8
        $result = DynamoDb::table($this->model->getTable())
611 8
            ->setItem(DynamoDb::marshalItem($this->model->getAttributes()))
612 8
            ->prepare($this->client)
613 8
            ->putItem();
614
615 8
        return array_get($result, '@metadata.statusCode') === 200;
616
    }
617
618 55
    public function get($columns = [])
619
    {
620 55
        return $this->all($columns);
621
    }
622
623 67
    public function all($columns = [])
624
    {
625 67
        $limit = isset($this->limit) ? $this->limit : static::MAX_LIMIT;
626 67
        return $this->getAll($columns, $limit, !isset($this->limit));
627
    }
628
629 4
    public function count()
630
    {
631 4
        $limit = isset($this->limit) ? $this->limit : static::MAX_LIMIT;
632 4
        $raw = $this->toDynamoDbQuery(['count(*)'], $limit);
633
634 4
        if ($raw->op === 'Scan') {
635 4
            $res = $this->client->scan($raw->query);
636
        } else {
637
            $res = $this->client->query($raw->query);
638
        }
639
640 4
        return $res['Count'];
641
    }
642
643 4
    public function decorate(Closure $closure)
644
    {
645 4
        $this->decorator = $closure;
646 4
        return $this;
647
    }
648
649 86
    protected function getAll(
650
        $columns = [],
651
        $limit = DynamoDbQueryBuilder::MAX_LIMIT,
652
        $useIterator = DynamoDbQueryBuilder::DEFAULT_TO_ITERATOR
653
    ) {
654 86
        $analyzer = $this->getConditionAnalyzer();
655
656 86
        if ($analyzer->isExactSearch()) {
657 7
            $item = $this->find($analyzer->identifierConditionValues(), $columns);
658
659 7
            return $this->getModel()->newCollection([$item]);
660
        }
661
662 80
        $raw = $this->toDynamoDbQuery($columns, $limit);
663
664 80
        if ($useIterator) {
665 65
            $iterator = $this->client->getIterator($raw->op, $raw->query);
666
667 65
            if (isset($raw->query['Limit'])) {
668 12
                $iterator = new \LimitIterator($iterator, 0, $raw->query['Limit']);
669
            }
670
        } else {
671 19
            if ($raw->op === 'Scan') {
672 16
                $res = $this->client->scan($raw->query);
673
            } else {
674 3
                $res = $this->client->query($raw->query);
675
            }
676
677 19
            $this->lastEvaluatedKey = array_get($res, 'LastEvaluatedKey');
678 19
            $iterator = $res['Items'];
679
        }
680
681 80
        $results = [];
682
683 80
        foreach ($iterator as $item) {
684 80
            $item = DynamoDb::unmarshalItem($item);
685 80
            $model = $this->model->newInstance([], true);
686 80
            $model->setRawAttributes($item, true);
687 80
            $results[] = $model;
688
        }
689
690 80
        return $this->getModel()->newCollection($results, $analyzer->index());
691
    }
692
693
    /**
694
     * Return the raw DynamoDb query
695
     *
696
     * @param array $columns
697
     * @param int $limit
698
     * @return RawDynamoDbQuery
699
     */
700 90
    public function toDynamoDbQuery(
701
        $columns = [],
702
        $limit = DynamoDbQueryBuilder::MAX_LIMIT
703
    ) {
704 90
        $this->applyScopes();
705
706 90
        $this->resetExpressions();
707
708 90
        $op = 'Scan';
709 90
        $queryBuilder = DynamoDb::table($this->model->getTable());
710
711 90
        if (! empty($this->wheres)) {
712 70
            $analyzer = $this->getConditionAnalyzer();
713
714 70
            if ($keyConditions = $analyzer->keyConditions()) {
715 16
                $op = 'Query';
716 16
                $queryBuilder->setKeyConditionExpression($this->keyConditionExpression->parse($keyConditions));
717
            }
718
719 70
            if ($filterConditions = $analyzer->filterConditions()) {
720 61
                $queryBuilder->setFilterExpression($this->filterExpression->parse($filterConditions));
721
            }
722
723 70
            if ($index = $analyzer->index()) {
724 8
                $queryBuilder->setIndexName($index->name);
725
            }
726
        }
727
728 90
        if ($this->index) {
729
            // If user specifies the index manually, respect that
730 1
            $queryBuilder->setIndexName($this->index);
731
        }
732
733 90
        if ($limit !== static::MAX_LIMIT) {
734 31
            $queryBuilder->setLimit($limit);
735
        }
736
737 90
        if (!empty($columns)) {
738
            // Either we try to get the count or specific columns
739 8
            if ($columns == ['count(*)']) {
740 6
                $queryBuilder->setSelect('COUNT');
741
            } else {
742 2
                $queryBuilder->setProjectionExpression($this->projectionExpression->parse($columns));
743
            }
744
        }
745
746 90
        if (!empty($this->lastEvaluatedKey)) {
747 15
            $queryBuilder->setExclusiveStartKey($this->lastEvaluatedKey);
748
        }
749
750
        $queryBuilder
751 90
            ->setExpressionAttributeNames($this->expressionAttributeNames->all())
752 90
            ->setExpressionAttributeValues($this->expressionAttributeValues->all());
753
754 90
        $raw = new RawDynamoDbQuery($op, $queryBuilder->prepare($this->client)->query);
755
756 90
        if ($this->decorator) {
757 4
            call_user_func($this->decorator, $raw);
758
        }
759
760 90
        return $raw;
761
    }
762
763
    /**
764
     * @return Analyzer
765
     */
766 95
    protected function getConditionAnalyzer()
767
    {
768 95
        return with(new Analyzer)
769 95
            ->on($this->model)
770 95
            ->withIndex($this->index)
771 95
            ->analyze($this->wheres);
772
    }
773
774 34
    protected function isMultipleIds($id)
775
    {
776 34
        $keys = collect($this->model->getKeyNames());
777
778
        // could be ['id' => 'foo'], ['id1' => 'foo', 'id2' => 'bar']
779
        $single = $keys->first(function ($name) use ($id) {
780 34
            return !isset($id[$name]);
781 34
        }) === null;
782
783 34
        if ($single) {
784 19
            return false;
785
        }
786
787
        // could be ['foo', 'bar'], [['id1' => 'foo', 'id2' => 'bar'], ...]
788 15
        return $this->model->hasCompositeKey() ? is_array(array_first($id)) : is_array($id);
789
    }
790
791
    /**
792
     * @return DynamoDbModel
793
     */
794 86
    public function getModel()
795
    {
796 86
        return $this->model;
797
    }
798
799
    /**
800
     * @return \Aws\DynamoDb\DynamoDbClient
801
     */
802
    public function getClient()
803
    {
804
        return $this->client;
805
    }
806
807
    /**
808
     * Register a new global scope.
809
     *
810
     * @param  string  $identifier
811
     * @param  \Illuminate\Database\Eloquent\Scope|\Closure  $scope
812
     * @return $this
813
     */
814 7
    public function withGlobalScope($identifier, $scope)
815
    {
816 7
        $this->scopes[$identifier] = $scope;
817
818 7
        if (method_exists($scope, 'extend')) {
819
            $scope->extend($this);
820
        }
821
822 7
        return $this;
823
    }
824
825
    /**
826
     * Remove a registered global scope.
827
     *
828
     * @param  \Illuminate\Database\Eloquent\Scope|string  $scope
829
     * @return $this
830
     */
831 3
    public function withoutGlobalScope($scope)
832
    {
833 3
        if (! is_string($scope)) {
834
            $scope = get_class($scope);
835
        }
836
837 3
        unset($this->scopes[$scope]);
838
839 3
        $this->removedScopes[] = $scope;
840
841 3
        return $this;
842
    }
843
844
    /**
845
     * Remove all or passed registered global scopes.
846
     *
847
     * @param  array|null  $scopes
848
     * @return $this
849
     */
850 5
    public function withoutGlobalScopes(array $scopes = null)
851
    {
852 5
        if (is_array($scopes)) {
853
            foreach ($scopes as $scope) {
854
                $this->withoutGlobalScope($scope);
855
            }
856
        } else {
857 5
            $this->scopes = [];
858
        }
859
860 5
        return $this;
861
    }
862
863
    /**
864
     * Get an array of global scopes that were removed from the query.
865
     *
866
     * @return array
867
     */
868
    public function removedScopes()
869
    {
870
        return $this->removedScopes;
871
    }
872
873
    /**
874
     * Apply the scopes to the Eloquent builder instance and return it.
875
     *
876
     * @return DynamoDbQueryBuilder
877
     */
878 90
    public function applyScopes()
879
    {
880 90
        if (! $this->scopes) {
881 89
            return $this;
882
        }
883
884 3
        $builder = $this;
885
886 3
        foreach ($builder->scopes as $identifier => $scope) {
887 3
            if (! isset($builder->scopes[$identifier])) {
888
                continue;
889
            }
890
891
            $builder->callScope(function (DynamoDbQueryBuilder $builder) use ($scope) {
892
                // If the scope is a Closure we will just go ahead and call the scope with the
893
                // builder instance. The "callScope" method will properly group the clauses
894
                // that are added to this query so "where" clauses maintain proper logic.
895 3
                if ($scope instanceof Closure) {
896 3
                    $scope($builder);
897
                }
898
899
                // If the scope is a scope object, we will call the apply method on this scope
900
                // passing in the builder and the model instance. After we run all of these
901
                // scopes we will return back the builder instance to the outside caller.
902 3
                if ($scope instanceof Scope) {
903
                    throw new NotSupportedException('Scope object is not yet supported');
904
                }
905 3
            });
906
907 3
            $builder->withoutGlobalScope($identifier);
908
        }
909
910 3
        return $builder;
911
    }
912
913
    /**
914
     * Apply the given scope on the current builder instance.
915
     *
916
     * @param  callable  $scope
917
     * @param  array  $parameters
918
     * @return mixed
919
     */
920 7
    protected function callScope(callable $scope, $parameters = [])
921
    {
922 7
        array_unshift($parameters, $this);
923
924
        // $query = $this->getQuery();
925
926
        // // We will keep track of how many wheres are on the query before running the
927
        // // scope so that we can properly group the added scope constraints in the
928
        // // query as their own isolated nested where statement and avoid issues.
929
        // $originalWhereCount = is_null($query->wheres)
930
        //             ? 0 : count($query->wheres);
931
932 7
        $result = $scope(...array_values($parameters)) ?: $this;
933
934
        // if (count((array) $query->wheres) > $originalWhereCount) {
935
        //     $this->addNewWheresWithinGroup($query, $originalWhereCount);
936
        // }
937
938 7
        return $result;
939
    }
940
941
    /**
942
     * Dynamically handle calls into the query instance.
943
     *
944
     * @param  string  $method
945
     * @param  array  $parameters
946
     * @return mixed
947
     */
948 7
    public function __call($method, $parameters)
949
    {
950 7
        if (method_exists($this->model, $scope = 'scope'.ucfirst($method))) {
951 5
            return $this->callScope([$this->model, $scope], $parameters);
952
        }
953
954 2
        return $this;
955
    }
956
}
957