Test Failed
Pull Request — master (#272)
by Manabu
06:33
created

DynamoDbQueryBuilder::orWhereNotNull()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 0
Metric Value
eloc 1
c 0
b 0
f 0
dl 0
loc 3
ccs 0
cts 2
cp 0
rs 10
cc 1
nc 1
nop 1
crap 2
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 BaoPham\DynamoDb\H;
9
use Closure;
10
use Illuminate\Contracts\Support\Arrayable;
11
use Illuminate\Database\Eloquent\ModelNotFoundException;
12
use Illuminate\Database\Eloquent\Scope;
13
use Illuminate\Support\Arr;
14
15
class DynamoDbQueryBuilder
16
{
17
    use HasParsers;
18
19
    const MAX_LIMIT = -1;
20
    const DEFAULT_TO_ITERATOR = true;
21
22
    /**
23
     * The maximum number of records to return.
24
     *
25
     * @var int
26
     */
27
    public $limit;
28
29
    /**
30
     * @var array
31
     */
32
    public $wheres = [];
33
34
    /**
35
     * @var DynamoDbModel
36
     */
37
    protected $model;
38
39
    /**
40
     * @var \Aws\DynamoDb\DynamoDbClient
41
     */
42
    protected $client;
43
44
    /**
45
     * @var Closure
46
     */
47
    protected $decorator;
48
49
    /**
50
     * Applied global scopes.
51
     *
52
     * @var array
53
     */
54
    protected $scopes = [];
55
56
    /**
57
     * Removed global scopes.
58
     *
59
     * @var array
60
     */
61
    protected $removedScopes = [];
62
63
    /**
64
     * When not using the iterator, you can store the lastEvaluatedKey to
65
     * paginate through the results. The getAll method will take this into account
66
     * when used with $use_iterator = false.
67
     *
68
     * @var mixed
69
     */
70
    protected $lastEvaluatedKey;
71
72
    /**
73
     * Specified index name for the query.
74
     *
75
     * @var string
76
     */
77
    protected $index;
78
79 11
    public function __construct(DynamoDbModel $model)
80
    {
81 11
        $this->model = $model;
82 11
        $this->client = $model->getClient();
83 11
        $this->setupExpressions();
84 11
    }
85
86
    /**
87
     * Alias to set the "limit" value of the query.
88
     *
89
     * @param  int  $value
90
     * @return DynamoDbQueryBuilder
91
     */
92
    public function take($value)
93
    {
94
        return $this->limit($value);
95
    }
96
97
    /**
98
     * Set the "limit" value of the query.
99
     *
100
     * @param  int  $value
101
     * @return $this
102
     */
103
    public function limit($value)
104
    {
105
        $this->limit = $value;
106
107
        return $this;
108
    }
109
110
    /**
111
     * Alias to set the "offset" value of the query.
112
     *
113
     * @param  int $value
114
     * @throws NotSupportedException
115
     */
116
    public function skip($value)
117
    {
118
        return $this->offset($value);
119
    }
120
121
    /**
122
     * Set the "offset" value of the query.
123
     *
124
     * @param  int $value
125
     * @throws NotSupportedException
126
     */
127
    public function offset($value)
128
    {
129
        throw new NotSupportedException('Skip/Offset is not supported. Consider using after() instead');
130
    }
131
132
    /**
133
     * Determine the starting point (exclusively) of the query.
134
     * Unfortunately, offset of how many records to skip does not make sense for DynamoDb.
135
     * Instead, provide the last result of the previous query as the starting point for the next query.
136
     *
137
     * @param  DynamoDbModel|null  $after
138
     *   Examples:
139
     *
140
     *   For query such as
141
     *       $query = $model->where('count', 10)->limit(2);
142
     *       $last = $query->all()->last();
143
     *   Take the last item of this query result as the next "offset":
144
     *       $nextPage = $query->after($last)->limit(2)->all();
145
     *
146
     *   Alternatively, pass in nothing to reset the starting point.
147
     *
148
     * @return $this
149
     */
150
    public function after(DynamoDbModel $after = null)
151
    {
152
        if (empty($after)) {
153
            $this->lastEvaluatedKey = null;
154
155
            return $this;
156
        }
157
158
        $afterKey = $after->getKeys();
159
160
        $analyzer = $this->getConditionAnalyzer();
161
162
        if ($index = $analyzer->index()) {
163
            foreach ($index->columns() as $column) {
164
                $afterKey[$column] = $after->getAttribute($column);
165
            }
166
        }
167
168
        $this->lastEvaluatedKey = DynamoDb::marshalItem($afterKey);
169
170
        return $this;
171
    }
172
173
    /**
174
     * Similar to after(), but instead of using the model instance, the model's keys are used.
175
     * Use $collection->lastKey() or $model->getKeys() to retrieve the value.
176
     *
177
     * @param  Array  $key
178
     *   Examples:
179
     *
180
     *   For query such as
181
     *       $query = $model->where('count', 10)->limit(2);
182
     *       $items = $query->all();
183
     *   Take the last item of this query result as the next "offset":
184
     *       $nextPage = $query->afterKey($items->lastKey())->limit(2)->all();
185
     *
186
     *   Alternatively, pass in nothing to reset the starting point.
187
     *
188
     * @return $this
189
     */
190
    public function afterKey($key = null)
191
    {
192
        $this->lastEvaluatedKey = empty($key) ? null : DynamoDb::marshalItem($key);
193
        return $this;
194
    }
195
196
    /**
197
     * Set the index name manually
198
     *
199
     * @param string $index The index name
200
     * @return $this
201
     */
202 1
    public function withIndex($index)
203
    {
204 1
        $this->index = $index;
205 1
        return $this;
206
    }
207
208 7
    public function where($column, $operator = null, $value = null, $boolean = 'and')
209
    {
210
        // If the column is an array, we will assume it is an array of key-value pairs
211
        // and can add them each as a where clause. We will maintain the boolean we
212
        // received when the method was called and pass it into the nested where.
213 7
        if (is_array($column)) {
214 2
            foreach ($column as $key => $value) {
215 2
                $this->where($key, '=', $value, $boolean);
216
            }
217
218 2
            return $this;
219
        }
220
221
        // Here we will make some assumptions about the operator. If only 2 values are
222
        // passed to the method, we will assume that the operator is an equals sign
223
        // and keep going. Otherwise, we'll require the operator to be passed in.
224 7
        if (func_num_args() == 2) {
225 5
            list($value, $operator) = [$operator, '='];
226
        }
227
228
        // If the columns is actually a Closure instance, we will assume the developer
229
        // wants to begin a nested where statement which is wrapped in parenthesis.
230
        // We'll add that Closure to the query then return back out immediately.
231 7
        if ($column instanceof Closure) {
232
            return $this->whereNested($column, $boolean);
233
        }
234
235
        // If the given operator is not found in the list of valid operators we will
236
        // assume that the developer is just short-cutting the '=' operators and
237
        // we will set the operators to '=' and set the values appropriately.
238 7
        if (!ComparisonOperator::isValidOperator($operator)) {
239
            list($value, $operator) = [$operator, '='];
240
        }
241
242
        // If the value is a Closure, it means the developer is performing an entire
243
        // sub-select within the query and we will need to compile the sub-select
244
        // within the where clause to get the appropriate query record results.
245 7
        if ($value instanceof Closure) {
246
            throw new NotSupportedException('Closure in where clause is not supported');
247
        }
248
249 7
        $this->wheres[] = [
250 7
            'column' => $column,
251 7
            'type' => ComparisonOperator::getDynamoDbOperator($operator),
252 7
            'value' => $value,
253 7
            'boolean' => $boolean,
254
        ];
255
256 7
        return $this;
257
    }
258
259
    /**
260
     * Add a nested where statement to the query.
261
     *
262
     * @param  \Closure $callback
263
     * @param  string   $boolean
264
     * @return $this
265
     */
266
    public function whereNested(Closure $callback, $boolean = 'and')
267
    {
268
        call_user_func($callback, $query = $this->forNestedWhere());
269
270
        return $this->addNestedWhereQuery($query, $boolean);
271
    }
272
273
    /**
274
     * Create a new query instance for nested where condition.
275
     *
276
     * @return $this
277
     */
278
    public function forNestedWhere()
279
    {
280
        return $this->newQuery();
281
    }
282
283
    /**
284
     * Add another query builder as a nested where to the query builder.
285
     *
286
     * @param  DynamoDbQueryBuilder $query
287
     * @param  string  $boolean
288
     * @return $this
289
     */
290
    public function addNestedWhereQuery($query, $boolean = 'and')
291
    {
292
        if (count($query->wheres)) {
293
            $type = 'Nested';
294
            $column = null;
295
            $value = $query->wheres;
296
            $this->wheres[] = compact('column', 'type', 'value', 'boolean');
297
        }
298
299
        return $this;
300
    }
301
302
    /**
303
     * Add an "or where" clause to the query.
304
     *
305
     * @param  string  $column
306
     * @param  string  $operator
307
     * @param  mixed   $value
308
     * @return $this
309
     */
310
    public function orWhere($column, $operator = null, $value = null)
311
    {
312
        return $this->where($column, $operator, $value, 'or');
313
    }
314
315
    /**
316
     * Add a "where in" clause to the query.
317
     *
318
     * @param  string  $column
319
     * @param  mixed   $values
320
     * @param  string  $boolean
321
     * @param  bool    $not
322
     * @return $this
323
     * @throws NotSupportedException
324
     */
325
    public function whereIn($column, $values, $boolean = 'and', $not = false)
326
    {
327
        if ($not) {
328
            throw new NotSupportedException('"not in" is not a valid DynamoDB comparison operator');
329
        }
330
331
        // If the value is a query builder instance, not supported
332
        if ($values instanceof static) {
333
            throw new NotSupportedException('Value is a query builder instance');
334
        }
335
336
        // If the value of the where in clause is actually a Closure, not supported
337
        if ($values instanceof Closure) {
338
            throw new NotSupportedException('Value is a Closure');
339
        }
340
341
        // Next, if the value is Arrayable we need to cast it to its raw array form
342
        if ($values instanceof Arrayable) {
343
            $values = $values->toArray();
344
        }
345
346
        return $this->where($column, ComparisonOperator::IN, $values, $boolean);
347
    }
348
349
    /**
350
     * Add an "or where in" clause to the query.
351
     *
352
     * @param  string  $column
353
     * @param  mixed   $values
354
     * @return $this
355
     */
356
    public function orWhereIn($column, $values)
357
    {
358
        return $this->whereIn($column, $values, 'or');
359
    }
360
361
    /**
362
     * Add a "where null" clause to the query.
363
     *
364
     * @param  string  $column
365
     * @param  string  $boolean
366
     * @param  bool    $not
367
     * @return $this
368
     */
369
    public function whereNull($column, $boolean = 'and', $not = false)
370
    {
371
        $type = $not ? ComparisonOperator::NOT_NULL : ComparisonOperator::NULL;
372
373
        $this->wheres[] = compact('column', 'type', 'boolean');
374
375
        return $this;
376
    }
377
378
    /**
379
     * Add an "or where null" clause to the query.
380
     *
381
     * @param  string  $column
382
     * @return $this
383
     */
384
    public function orWhereNull($column)
385
    {
386
        return $this->whereNull($column, 'or');
387
    }
388
389
    /**
390
     * Add an "or where not null" clause to the query.
391
     *
392
     * @param  string  $column
393
     * @return $this
394
     */
395
    public function orWhereNotNull($column)
396
    {
397
        return $this->whereNotNull($column, 'or');
398
    }
399
400
    /**
401
     * Add a "where not null" clause to the query.
402
     *
403
     * @param  string  $column
404
     * @param  string  $boolean
405
     * @return $this
406
     */
407
    public function whereNotNull($column, $boolean = 'and')
408
    {
409
        return $this->whereNull($column, $boolean, true);
410
    }
411
412
    /**
413
     * Get a new instance of the query builder.
414
     *
415
     * @return DynamoDbQueryBuilder
416
     */
417
    public function newQuery()
418
    {
419
        return new static($this->getModel());
420
    }
421
422
    /**
423
     * Implements the Query Chunk method
424
     *
425
     * @param int $chunkSize
426
     * @param callable $callback
427
     */
428
    public function chunk($chunkSize, callable $callback)
429
    {
430
        while (true) {
431
            $results = $this->getAll([], $chunkSize, false);
432
433
            if (!$results->isEmpty()) {
434
                if (call_user_func($callback, $results) === false) {
435
                    return false;
436
                }
437
            }
438
439
            if (empty($this->lastEvaluatedKey)) {
440
                break;
441
            }
442
        }
443
444
        return true;
445
    }
446
447
    /**
448
     * @param $id
449
     * @param array $columns
450
     * @return DynamoDbModel|\Illuminate\Database\Eloquent\Collection|null
451
     */
452 4
    public function find($id, array $columns = [])
453
    {
454 4
        if ($this->isMultipleIds($id)) {
455
            return $this->findMany($id, $columns);
456
        }
457
458 4
        $this->resetExpressions();
459
460 4
        $this->model->setId($id);
461
462 4
        $query = DynamoDb::table($this->model->getTable())
463 4
            ->setKey(DynamoDb::marshalItem($this->model->getKeys()))
464 4
            ->setConsistentRead(true);
465
466 4
        if (!empty($columns)) {
467
            $query
468
                ->setProjectionExpression($this->projectionExpression->parse($columns))
469
                ->setExpressionAttributeNames($this->expressionAttributeNames->all());
470
        }
471
472 4
        $item = $query->prepare($this->client)->getItem();
473
474
        $item = Arr::get($item->toArray(), 'Item');
475
476
        if (empty($item)) {
477
            return null;
478
        }
479
480
        $item = DynamoDb::unmarshalItem($item);
481
482
        $model = $this->model->newInstance([], true);
483
484
        $model->setRawAttributes($item, true);
485
486
        return $model;
487
    }
488
489
    /**
490
     * @param $ids
491
     * @param array $columns
492
     * @return \Illuminate\Database\Eloquent\Collection
493
     */
494
    public function findMany($ids, array $columns = [])
495
    {
496
        $collection = $this->model->newCollection();
497
498
        if (empty($ids)) {
499
            return $collection;
500
        }
501
502
        $this->resetExpressions();
503
504
        $table = $this->model->getTable();
505
506
        $keys = collect($ids)->map(function ($id) {
507
            if (! is_array($id)) {
508
                $id = [$this->model->getKeyName() => $id];
509
            }
510
511
            return DynamoDb::marshalItem($id);
512
        });
513
514
        $subQuery = DynamoDb::newQuery()
515
            ->setKeys($keys->toArray())
516
            ->setProjectionExpression($this->projectionExpression->parse($columns))
517
            ->setExpressionAttributeNames($this->expressionAttributeNames->all())
518
            ->prepare($this->client)
519
            ->query;
520
521
        $results = DynamoDb::newQuery()
522
            ->setRequestItems([$table => $subQuery])
523
            ->prepare($this->client)
524
            ->batchGetItem();
525
526
        foreach ($results['Responses'][$table] as $item) {
527
            $item = DynamoDb::unmarshalItem($item);
528
            $model = $this->model->newInstance([], true);
529
            $model->setRawAttributes($item, true);
530
            $collection->add($model);
531
        }
532
533
        return $collection;
534
    }
535
536 2
    public function findOrFail($id, $columns = [])
537
    {
538 2
        $result = $this->find($id, $columns);
539
540
        if ($this->isMultipleIds($id)) {
541
            if (count($result) == count(array_unique($id))) {
0 ignored issues
show
Bug introduced by
$result of type BaoPham\DynamoDb\DynamoDbModel is incompatible with the type Countable|array expected by parameter $value of count(). ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

541
            if (count(/** @scrutinizer ignore-type */ $result) == count(array_unique($id))) {
Loading history...
542
                return $result;
543
            }
544
        } elseif (! is_null($result)) {
545
            return $result;
546
        }
547
548
        throw (new ModelNotFoundException)->setModel(
549
            get_class($this->model),
550
            $id
551
        );
552
    }
553
554 2
    public function first($columns = [])
555
    {
556 2
        $items = $this->getAll($columns, 1);
557
558
        return $items->first();
559
    }
560
561 2
    public function firstOrFail($columns = [])
562
    {
563 2
        if (! is_null($model = $this->first($columns))) {
564
            return $model;
565
        }
566
567
        throw (new ModelNotFoundException)->setModel(get_class($this->model));
568
    }
569
570
    /**
571
     * Remove attributes from an existing item
572
     *
573
     * @param array ...$attributes
574
     * @return bool
575
     * @throws InvalidQuery
576
     */
577
    public function removeAttribute(...$attributes)
578
    {
579
        $keySet = !empty(array_filter($this->model->getKeys()));
580
581
        if (!$keySet) {
582
            $analyzer = $this->getConditionAnalyzer();
583
584
            if (!$analyzer->isExactSearch()) {
585
                throw new InvalidQuery('Need to provide the key in your query');
586
            }
587
588
            $id = $analyzer->identifierConditionValues();
589
            $this->model->setId($id);
590
        }
591
592
        $key = DynamoDb::marshalItem($this->model->getKeys());
593
594
        $this->resetExpressions();
595
596
        /** @var \Aws\Result $result */
597
        $result = DynamoDb::table($this->model->getTable())
598
            ->setKey($key)
599
            ->setUpdateExpression($this->updateExpression->remove($attributes))
600
            ->setExpressionAttributeNames($this->expressionAttributeNames->all())
601
            ->setReturnValues('ALL_NEW')
602
            ->prepare($this->client)
603
            ->updateItem();
604
605
        $success = Arr::get($result, '@metadata.statusCode') === 200;
606
607
        if ($success) {
608
            $this->model->setRawAttributes(DynamoDb::unmarshalItem($result->get('Attributes')));
609
            $this->model->syncOriginal();
610
        }
611
612
        return $success;
613
    }
614
615
    public function delete()
616
    {
617
        $result = DynamoDb::table($this->model->getTable())
618
            ->setKey(DynamoDb::marshalItem($this->model->getKeys()))
619
            ->prepare($this->client)
620
            ->deleteItem();
621
622
        return Arr::get($result->toArray(), '@metadata.statusCode') === 200;
623
    }
624
625
    public function deleteAsync()
626
    {
627
        $promise = DynamoDb::table($this->model->getTable())
628
            ->setKey(DynamoDb::marshalItem($this->model->getKeys()))
629
            ->prepare($this->client)
630
            ->deleteItemAsync();
631
632
        return $promise;
633
    }
634
635
    public function save()
636
    {
637
        $result = DynamoDb::table($this->model->getTable())
638
            ->setItem(DynamoDb::marshalItem($this->model->getAttributes()))
639
            ->prepare($this->client)
640
            ->putItem();
641
642
        return Arr::get($result, '@metadata.statusCode') === 200;
643
    }
644
645
    public function saveAsync()
646
    {
647
        $promise = DynamoDb::table($this->model->getTable())
648
            ->setItem(DynamoDb::marshalItem($this->model->getAttributes()))
649
            ->prepare($this->client)
650
            ->putItemAsync();
651
652
        return $promise;
653
    }
654
655
    public function get($columns = [])
656
    {
657
        return $this->all($columns);
658
    }
659
660
    public function all($columns = [])
661
    {
662
        $limit = isset($this->limit) ? $this->limit : static::MAX_LIMIT;
663
        return $this->getAll($columns, $limit, !isset($this->limit));
664
    }
665
666
    public function count()
667
    {
668
        $limit = isset($this->limit) ? $this->limit : static::MAX_LIMIT;
669
        $raw = $this->toDynamoDbQuery(['count(*)'], $limit);
670
671
        if ($raw->op === 'Scan') {
672
            $res = $this->client->scan($raw->query);
673
        } else {
674
            $res = $this->client->query($raw->query);
675
        }
676
677
        return $res['Count'];
678
    }
679
680 2
    public function decorate(Closure $closure)
681
    {
682 2
        $this->decorator = $closure;
683 2
        return $this;
684
    }
685
686 2
    protected function getAll(
687
        $columns = [],
688
        $limit = DynamoDbQueryBuilder::MAX_LIMIT,
689
        $useIterator = DynamoDbQueryBuilder::DEFAULT_TO_ITERATOR
690
    ) {
691 2
        $analyzer = $this->getConditionAnalyzer();
692
693 2
        if ($analyzer->isExactSearch()) {
694 2
            $item = $this->find($analyzer->identifierConditionValues(), $columns);
695
696
            return $this->getModel()->newCollection([$item]);
697
        }
698
699
        $raw = $this->toDynamoDbQuery($columns, $limit);
700
701
        if ($useIterator) {
702
            $iterator = $this->client->getIterator($raw->op, $raw->query);
703
704
            if (isset($raw->query['Limit'])) {
705
                $iterator = new \LimitIterator($iterator, 0, $raw->query['Limit']);
706
            }
707
        } else {
708
            if ($raw->op === 'Scan') {
709
                $res = $this->client->scan($raw->query);
710
            } else {
711
                $res = $this->client->query($raw->query);
712
            }
713
714
            $this->lastEvaluatedKey = Arr::get($res, 'LastEvaluatedKey');
715
            $iterator = $res['Items'];
716
        }
717
718
        $results = [];
719
720
        foreach ($iterator as $item) {
721
            $item = DynamoDb::unmarshalItem($item);
722
            $model = $this->model->newInstance([], true);
723
            $model->setRawAttributes($item, true);
724
            $results[] = $model;
725
        }
726
727
        return $this->getModel()->newCollection($results, $analyzer->index());
728
    }
729
730
    /**
731
     * Return the raw DynamoDb query
732
     *
733
     * @param array $columns
734
     * @param int $limit
735
     * @return RawDynamoDbQuery
736
     */
737 5
    public function toDynamoDbQuery(
738
        $columns = [],
739
        $limit = DynamoDbQueryBuilder::MAX_LIMIT
740
    ) {
741 5
        $this->applyScopes();
742
743 5
        $this->resetExpressions();
744
745 5
        $op = 'Scan';
746 5
        $queryBuilder = DynamoDb::table($this->model->getTable());
747
748 5
        if (! empty($this->wheres)) {
749 3
            $analyzer = $this->getConditionAnalyzer();
750
751 3
            if ($keyConditions = $analyzer->keyConditions()) {
752 1
                $op = 'Query';
753 1
                $queryBuilder->setKeyConditionExpression($this->keyConditionExpression->parse($keyConditions));
754
            }
755
756 3
            if ($filterConditions = $analyzer->filterConditions()) {
757 2
                $queryBuilder->setFilterExpression($this->filterExpression->parse($filterConditions));
758
            }
759
760 3
            if ($index = $analyzer->index()) {
761 1
                $queryBuilder->setIndexName($index->name);
762
            }
763
        }
764
765 5
        if ($this->index) {
766
            // If user specifies the index manually, respect that
767 1
            $queryBuilder->setIndexName($this->index);
768
        }
769
770 5
        if ($limit !== static::MAX_LIMIT) {
771
            $queryBuilder->setLimit($limit);
772
        }
773
774 5
        if (!empty($columns)) {
775
            // Either we try to get the count or specific columns
776 2
            if ($columns == ['count(*)']) {
777 2
                $queryBuilder->setSelect('COUNT');
778
            } else {
779
                $queryBuilder->setProjectionExpression($this->projectionExpression->parse($columns));
780
            }
781
        }
782
783 5
        if (!empty($this->lastEvaluatedKey)) {
784
            $queryBuilder->setExclusiveStartKey($this->lastEvaluatedKey);
785
        }
786
787
        $queryBuilder
788 5
            ->setExpressionAttributeNames($this->expressionAttributeNames->all())
789 5
            ->setExpressionAttributeValues($this->expressionAttributeValues->all());
790
791 5
        $raw = new RawDynamoDbQuery($op, $queryBuilder->prepare($this->client)->query);
792
793 5
        if ($this->decorator) {
794 2
            call_user_func($this->decorator, $raw);
795
        }
796
797 5
        return $raw;
798
    }
799
800
    /**
801
     * @return Analyzer
802
     */
803 5
    protected function getConditionAnalyzer()
804
    {
805 5
        return with(new Analyzer)
806 5
            ->on($this->model)
807 5
            ->withIndex($this->index)
808 5
            ->analyze($this->wheres);
809
    }
810
811 4
    protected function isMultipleIds($id)
812
    {
813 4
        $keys = collect($this->model->getKeyNames());
814
815
        // could be ['id' => 'foo'], ['id1' => 'foo', 'id2' => 'bar']
816
        $single = $keys->first(function ($name) use ($id) {
817 4
            return !isset($id[$name]);
818 4
        }) === null;
819
820 4
        if ($single) {
821 3
            return false;
822
        }
823
824
        // could be ['foo', 'bar'], [['id1' => 'foo', 'id2' => 'bar'], ...]
825 1
        return $this->model->hasCompositeKey() ? is_array(H::array_first($id)) : is_array($id);
826
    }
827
828
    /**
829
     * @return DynamoDbModel
830
     */
831
    public function getModel()
832
    {
833
        return $this->model;
834
    }
835
836
    /**
837
     * @return \Aws\DynamoDb\DynamoDbClient
838
     */
839
    public function getClient()
840
    {
841
        return $this->client;
842
    }
843
844
    /**
845
     * Register a new global scope.
846
     *
847
     * @param  string  $identifier
848
     * @param  \Illuminate\Database\Eloquent\Scope|\Closure  $scope
849
     * @return $this
850
     */
851
    public function withGlobalScope($identifier, $scope)
852
    {
853
        $this->scopes[$identifier] = $scope;
854
855
        if (method_exists($scope, 'extend')) {
856
            $scope->extend($this);
857
        }
858
859
        return $this;
860
    }
861
862
    /**
863
     * Remove a registered global scope.
864
     *
865
     * @param  \Illuminate\Database\Eloquent\Scope|string  $scope
866
     * @return $this
867
     */
868
    public function withoutGlobalScope($scope)
869
    {
870
        if (! is_string($scope)) {
871
            $scope = get_class($scope);
872
        }
873
874
        unset($this->scopes[$scope]);
875
876
        $this->removedScopes[] = $scope;
877
878
        return $this;
879
    }
880
881
    /**
882
     * Remove all or passed registered global scopes.
883
     *
884
     * @param  array|null  $scopes
885
     * @return $this
886
     */
887
    public function withoutGlobalScopes(array $scopes = null)
888
    {
889
        if (is_array($scopes)) {
890
            foreach ($scopes as $scope) {
891
                $this->withoutGlobalScope($scope);
892
            }
893
        } else {
894
            $this->scopes = [];
895
        }
896
897
        return $this;
898
    }
899
900
    /**
901
     * Get an array of global scopes that were removed from the query.
902
     *
903
     * @return array
904
     */
905
    public function removedScopes()
906
    {
907
        return $this->removedScopes;
908
    }
909
910
    /**
911
     * Apply the scopes to the Eloquent builder instance and return it.
912
     *
913
     * @return DynamoDbQueryBuilder
914
     */
915 5
    public function applyScopes()
916
    {
917 5
        if (! $this->scopes) {
918 5
            return $this;
919
        }
920
921
        $builder = $this;
922
923
        foreach ($builder->scopes as $identifier => $scope) {
924
            if (! isset($builder->scopes[$identifier])) {
925
                continue;
926
            }
927
928
            $builder->callScope(function (DynamoDbQueryBuilder $builder) use ($scope) {
929
                // If the scope is a Closure we will just go ahead and call the scope with the
930
                // builder instance. The "callScope" method will properly group the clauses
931
                // that are added to this query so "where" clauses maintain proper logic.
932
                if ($scope instanceof Closure) {
933
                    $scope($builder);
934
                }
935
936
                // If the scope is a scope object, we will call the apply method on this scope
937
                // passing in the builder and the model instance. After we run all of these
938
                // scopes we will return back the builder instance to the outside caller.
939
                if ($scope instanceof Scope) {
940
                    throw new NotSupportedException('Scope object is not yet supported');
941
                }
942
            });
943
944
            $builder->withoutGlobalScope($identifier);
945
        }
946
947
        return $builder;
948
    }
949
950
    /**
951
     * Apply the given scope on the current builder instance.
952
     *
953
     * @param  callable  $scope
954
     * @param  array  $parameters
955
     * @return mixed
956
     */
957
    protected function callScope(callable $scope, $parameters = [])
958
    {
959
        array_unshift($parameters, $this);
960
961
        // $query = $this->getQuery();
962
963
        // // We will keep track of how many wheres are on the query before running the
964
        // // scope so that we can properly group the added scope constraints in the
965
        // // query as their own isolated nested where statement and avoid issues.
966
        // $originalWhereCount = is_null($query->wheres)
967
        //             ? 0 : count($query->wheres);
968
969
        $result = $scope(...array_values($parameters)) ?: $this;
970
971
        // if (count((array) $query->wheres) > $originalWhereCount) {
972
        //     $this->addNewWheresWithinGroup($query, $originalWhereCount);
973
        // }
974
975
        return $result;
976
    }
977
978
    /**
979
     * Dynamically handle calls into the query instance.
980
     *
981
     * @param  string  $method
982
     * @param  array  $parameters
983
     * @return mixed
984
     */
985 2
    public function __call($method, $parameters)
986
    {
987 2
        if (method_exists($this->model, $scope = 'scope'.ucfirst($method))) {
988
            return $this->callScope([$this->model, $scope], $parameters);
989
        }
990
991 2
        return $this;
992
    }
993
}
994