Passed
Pull Request — master (#259)
by
unknown
07:11
created

DynamoDbQueryBuilder::pagedCount()   A

Complexity

Conditions 3
Paths 4

Size

Total Lines 14
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 12

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 8
c 1
b 0
f 0
dl 0
loc 14
ccs 0
cts 8
cp 0
rs 10
cc 3
nc 4
nop 0
crap 12
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 131
    public function __construct(DynamoDbModel $model)
80
    {
81 131
        $this->model = $model;
82 131
        $this->client = $model->getClient();
83 131
        $this->setupExpressions();
84 131
    }
85
86
    /**
87
     * Alias to set the "limit" value of the query.
88
     *
89
     * @param  int  $value
90
     * @return DynamoDbQueryBuilder
91
     */
92 6
    public function take($value)
93
    {
94 6
        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 14
    public function limit($value)
104
    {
105 14
        $this->limit = $value;
106
107 14
        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 4
    public function after(DynamoDbModel $after = null)
151
    {
152 4
        if (empty($after)) {
153 4
            $this->lastEvaluatedKey = null;
154
155 4
            return $this;
156
        }
157
158 4
        $afterKey = $after->getKeys();
159
160 4
        $analyzer = $this->getConditionAnalyzer();
161
162 4
        if ($index = $analyzer->index()) {
163 1
            foreach ($index->columns() as $column) {
164 1
                $afterKey[$column] = $after->getAttribute($column);
165
            }
166
        }
167
168 4
        $this->lastEvaluatedKey = DynamoDb::marshalItem($afterKey);
169
170 4
        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 4
    public function afterKey($key = null)
191
    {
192 4
        $this->lastEvaluatedKey = empty($key) ? null : DynamoDb::marshalItem($key);
193 4
        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 76
    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 76
        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 76
        if (func_num_args() == 2) {
225 45
            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 76
        if ($column instanceof Closure) {
232 2
            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 76
        if (!ComparisonOperator::isValidOperator($operator)) {
239 4
            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 76
        if ($value instanceof Closure) {
246
            throw new NotSupportedException('Closure in where clause is not supported');
247
        }
248
249 76
        $this->wheres[] = [
250 76
            'column' => $column,
251 76
            'type' => ComparisonOperator::getDynamoDbOperator($operator),
252 76
            'value' => $value,
253 76
            'boolean' => $boolean,
254
        ];
255
256 76
        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 2
    public function whereNested(Closure $callback, $boolean = 'and')
267
    {
268 2
        call_user_func($callback, $query = $this->forNestedWhere());
269
270 2
        return $this->addNestedWhereQuery($query, $boolean);
271
    }
272
273
    /**
274
     * Create a new query instance for nested where condition.
275
     *
276
     * @return $this
277
     */
278 2
    public function forNestedWhere()
279
    {
280 2
        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 2
    public function addNestedWhereQuery($query, $boolean = 'and')
291
    {
292 2
        if (count($query->wheres)) {
293 2
            $type = 'Nested';
294 2
            $column = null;
295 2
            $value = $query->wheres;
296 2
            $this->wheres[] = compact('column', 'type', 'value', 'boolean');
297
        }
298
299 2
        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 22
    public function orWhere($column, $operator = null, $value = null)
311
    {
312 22
        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 2
    public function whereIn($column, $values, $boolean = 'and', $not = false)
326
    {
327 2
        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 2
        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 2
        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 2
        if ($values instanceof Arrayable) {
343
            $values = $values->toArray();
344
        }
345
346 2
        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 2
    public function orWhereIn($column, $values)
357
    {
358 2
        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 4
    public function whereNull($column, $boolean = 'and', $not = false)
370
    {
371 4
        $type = $not ? ComparisonOperator::NOT_NULL : ComparisonOperator::NULL;
372
373 4
        $this->wheres[] = compact('column', 'type', 'boolean');
374
375 4
        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 2
    public function orWhereNull($column)
385
    {
386 2
        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 2
    public function orWhereNotNull($column)
396
    {
397 2
        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 2
    public function whereNotNull($column, $boolean = 'and')
408
    {
409 2
        return $this->whereNull($column, $boolean, true);
410
    }
411
412
    /**
413
     * Get a new instance of the query builder.
414
     *
415
     * @return DynamoDbQueryBuilder
416
     */
417 2
    public function newQuery()
418
    {
419 2
        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 9
    public function chunk($chunkSize, callable $callback)
429
    {
430 9
        while (true) {
431 9
            $results = $this->getAll([], $chunkSize, false);
432
433 9
            if (!$results->isEmpty()) {
434 9
                if (call_user_func($callback, $results) === false) {
435 2
                    return false;
436
                }
437
            }
438
439 7
            if (empty($this->lastEvaluatedKey)) {
440 7
                break;
441
            }
442
        }
443
444 7
        return true;
445
    }
446
447
    /**
448
     * @param $id
449
     * @param array $columns
450
     * @return DynamoDbModel|\Illuminate\Database\Eloquent\Collection|null
451
     */
452 40
    public function find($id, array $columns = [])
453
    {
454 40
        if ($this->isMultipleIds($id)) {
455 4
            return $this->findMany($id, $columns);
456
        }
457
458 36
        $this->resetExpressions();
459
460 36
        $this->model->setId($id);
461
462 36
        $query = DynamoDb::table($this->model->getTable())
463 36
            ->setKey(DynamoDb::marshalItem($this->model->getKeys()))
464 36
            ->setConsistentRead(true);
465
466 36
        if (!empty($columns)) {
467
            $query
468 3
                ->setProjectionExpression($this->projectionExpression->parse($columns))
469 3
                ->setExpressionAttributeNames($this->expressionAttributeNames->all());
470
        }
471
472 36
        $item = $query->prepare($this->client)->getItem();
473
474 36
        $item = Arr::get($item->toArray(), 'Item');
475
476 36
        if (empty($item)) {
477 4
            return null;
478
        }
479
480 32
        $item = DynamoDb::unmarshalItem($item);
481
482 32
        $model = $this->model->newInstance([], true);
483
484 32
        $model->setRawAttributes($item, true);
485
486 32
        return $model;
487
    }
488
489
    /**
490
     * @param $ids
491
     * @param array $columns
492
     * @return \Illuminate\Database\Eloquent\Collection
493
     */
494 4
    public function findMany($ids, array $columns = [])
495
    {
496 4
        $collection = $this->model->newCollection();
497
498 4
        if (empty($ids)) {
499
            return $collection;
500
        }
501
502 4
        $this->resetExpressions();
503
504 4
        $table = $this->model->getTable();
505
506
        $keys = collect($ids)->map(function ($id) {
507 4
            if (! is_array($id)) {
508 2
                $id = [$this->model->getKeyName() => $id];
509
            }
510
511 4
            return DynamoDb::marshalItem($id);
512 4
        });
513
514 4
        $subQuery = DynamoDb::newQuery()
515 4
            ->setKeys($keys->toArray())
516 4
            ->setProjectionExpression($this->projectionExpression->parse($columns))
517 4
            ->setExpressionAttributeNames($this->expressionAttributeNames->all())
518 4
            ->prepare($this->client)
519 4
            ->query;
520
521 4
        $results = DynamoDb::newQuery()
522 4
            ->setRequestItems([$table => $subQuery])
523 4
            ->prepare($this->client)
524 4
            ->batchGetItem();
525
526 4
        foreach ($results['Responses'][$table] as $item) {
527 4
            $item = DynamoDb::unmarshalItem($item);
528 4
            $model = $this->model->newInstance([], true);
529 4
            $model->setRawAttributes($item, true);
530 4
            $collection->add($model);
531
        }
532
533 4
        return $collection;
534
    }
535
536 5
    public function findOrFail($id, $columns = [])
537
    {
538 5
        $result = $this->find($id, $columns);
539
540 5
        if ($this->isMultipleIds($id)) {
541 1
            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 1
                return $result;
543
            }
544 4
        } elseif (! is_null($result)) {
545 2
            return $result;
546
        }
547
548 2
        throw (new ModelNotFoundException)->setModel(
549 2
            get_class($this->model),
550 2
            $id
551
        );
552
    }
553
554 16
    public function first($columns = [])
555
    {
556 16
        $items = $this->getAll($columns, 1);
557
558 16
        return $items->first();
559
    }
560
561 6
    public function firstOrFail($columns = [])
562
    {
563 6
        if (! is_null($model = $this->first($columns))) {
564 4
            return $model;
565
        }
566
567 2
        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 6
    public function removeAttribute(...$attributes)
578
    {
579 6
        $keySet = !empty(array_filter($this->model->getKeys()));
580
581 6
        if (!$keySet) {
582 4
            $analyzer = $this->getConditionAnalyzer();
583
584 4
            if (!$analyzer->isExactSearch()) {
585
                throw new InvalidQuery('Need to provide the key in your query');
586
            }
587
588 4
            $id = $analyzer->identifierConditionValues();
589 4
            $this->model->setId($id);
590
        }
591
592 6
        $key = DynamoDb::marshalItem($this->model->getKeys());
593
594 6
        $this->resetExpressions();
595
596
        /** @var \Aws\Result $result */
597 6
        $result = DynamoDb::table($this->model->getTable())
598 6
            ->setKey($key)
599 6
            ->setUpdateExpression($this->updateExpression->remove($attributes))
600 6
            ->setExpressionAttributeNames($this->expressionAttributeNames->all())
601 6
            ->setReturnValues('ALL_NEW')
602 6
            ->prepare($this->client)
603 6
            ->updateItem();
604
605 6
        $success = Arr::get($result, '@metadata.statusCode') === 200;
606
607 6
        if ($success) {
608 6
            $this->model->setRawAttributes(DynamoDb::unmarshalItem($result->get('Attributes')));
609 6
            $this->model->syncOriginal();
610
        }
611
612 6
        return $success;
613
    }
614
615 2
    public function delete()
616
    {
617 2
        $result = DynamoDb::table($this->model->getTable())
618 2
            ->setKey(DynamoDb::marshalItem($this->model->getKeys()))
619 2
            ->prepare($this->client)
620 2
            ->deleteItem();
621
622 2
        return Arr::get($result->toArray(), '@metadata.statusCode') === 200;
623
    }
624
625 2
    public function deleteAsync()
626
    {
627 2
        $promise = DynamoDb::table($this->model->getTable())
628 2
            ->setKey(DynamoDb::marshalItem($this->model->getKeys()))
629 2
            ->prepare($this->client)
630 2
            ->deleteItemAsync();
631
632 2
        return $promise;
633
    }
634
635 8
    public function save()
636
    {
637 8
        $result = DynamoDb::table($this->model->getTable())
638 8
            ->setItem(DynamoDb::marshalItem($this->model->getAttributes()))
639 8
            ->prepare($this->client)
640 8
            ->putItem();
641
642 8
        return Arr::get($result, '@metadata.statusCode') === 200;
643
    }
644
645 6
    public function saveAsync()
646
    {
647 6
        $promise = DynamoDb::table($this->model->getTable())
648 6
            ->setItem(DynamoDb::marshalItem($this->model->getAttributes()))
649 6
            ->prepare($this->client)
650 6
            ->putItemAsync();
651
652 6
        return $promise;
653
    }
654
655 55
    public function get($columns = [])
656
    {
657 55
        return $this->all($columns);
658
    }
659
660 67
    public function all($columns = [])
661
    {
662 67
        $limit = isset($this->limit) ? $this->limit : static::MAX_LIMIT;
663 67
        return $this->getAll($columns, $limit, !isset($this->limit));
664
    }
665
666 4
    public function count()
667
    {
668 4
        $limit = isset($this->limit) ? $this->limit : static::MAX_LIMIT;
669 4
        $raw = $this->toDynamoDbQuery(['count(*)'], $limit);
670
671 4
        if ($raw->op === 'Scan') {
672 4
            $res = $this->client->scan($raw->query);
673
        } else {
674
            $res = $this->client->query($raw->query);
675
        }
676
677 4
        return $res['Count'];
678
    }
679
    
680
    public function pagedCount()
681
    {
682
        $limit = isset($this->limit) ? $this->limit : static::MAX_LIMIT;
683
684
        $raw = $this->toDynamoDbQuery(['count(*)'], $limit);
685
    
686
        if ($raw->op === 'Scan') {
687
            $res = $this->client->scan($raw->query);
688
        } else {
689
            $res = $this->client->query($raw->query);
690
        }
691
        $this->lastEvaluatedKey = Arr::get($res, 'LastEvaluatedKey');
692
        
693
        return (object)['count' => $res['Count'], 'scanned_count' => $res['ScannedCount'], 'lastKey' => $this->lastEvaluatedKey];
694
    }
695
696 4
    public function decorate(Closure $closure)
697
    {
698 4
        $this->decorator = $closure;
699 4
        return $this;
700
    }
701
702 88
    protected function getAll(
703
        $columns = [],
704
        $limit = DynamoDbQueryBuilder::MAX_LIMIT,
705
        $useIterator = DynamoDbQueryBuilder::DEFAULT_TO_ITERATOR
706
    ) {
707 88
        $analyzer = $this->getConditionAnalyzer();
708
709 88
        if ($analyzer->isExactSearch()) {
710 7
            $item = $this->find($analyzer->identifierConditionValues(), $columns);
711
712 7
            return $this->getModel()->newCollection([$item]);
713
        }
714
715 82
        $raw = $this->toDynamoDbQuery($columns, $limit);
716
717 82
        if ($useIterator) {
718 65
            $iterator = $this->client->getIterator($raw->op, $raw->query);
719
720 65
            if (isset($raw->query['Limit'])) {
721 65
                $iterator = new \LimitIterator($iterator, 0, $raw->query['Limit']);
722
            }
723
        } else {
724 21
            if ($raw->op === 'Scan') {
725 18
                $res = $this->client->scan($raw->query);
726
            } else {
727 3
                $res = $this->client->query($raw->query);
728
            }
729
730 21
            $this->lastEvaluatedKey = Arr::get($res, 'LastEvaluatedKey');
731 21
            $iterator = $res['Items'];
732
        }
733
734 82
        $results = [];
735
736 82
        foreach ($iterator as $item) {
737 82
            $item = DynamoDb::unmarshalItem($item);
738 82
            $model = $this->model->newInstance([], true);
739 82
            $model->setRawAttributes($item, true);
740 82
            $results[] = $model;
741
        }
742
743 82
        return $this->getModel()->newCollection($results, $analyzer->index());
744
    }
745
746
    /**
747
     * Return the raw DynamoDb query
748
     *
749
     * @param array $columns
750
     * @param int $limit
751
     * @return RawDynamoDbQuery
752
     */
753 92
    public function toDynamoDbQuery(
754
        $columns = [],
755
        $limit = DynamoDbQueryBuilder::MAX_LIMIT
756
    ) {
757 92
        $this->applyScopes();
758
759 92
        $this->resetExpressions();
760
761 92
        $op = 'Scan';
762 92
        $queryBuilder = DynamoDb::table($this->model->getTable());
763
764 92
        if (! empty($this->wheres)) {
765 70
            $analyzer = $this->getConditionAnalyzer();
766
767 70
            if ($keyConditions = $analyzer->keyConditions()) {
768 16
                $op = 'Query';
769 16
                $queryBuilder->setKeyConditionExpression($this->keyConditionExpression->parse($keyConditions));
770
            }
771
772 70
            if ($filterConditions = $analyzer->filterConditions()) {
773 61
                $queryBuilder->setFilterExpression($this->filterExpression->parse($filterConditions));
774
            }
775
776 70
            if ($index = $analyzer->index()) {
777 8
                $queryBuilder->setIndexName($index->name);
778
            }
779
        }
780
781 92
        if ($this->index) {
782
            // If user specifies the index manually, respect that
783 1
            $queryBuilder->setIndexName($this->index);
784
        }
785
786 92
        if ($limit !== static::MAX_LIMIT) {
787 33
            $queryBuilder->setLimit($limit);
788
        }
789
790 92
        if (!empty($columns)) {
791
            // Either we try to get the count or specific columns
792 8
            if ($columns == ['count(*)']) {
793 6
                $queryBuilder->setSelect('COUNT');
794
            } else {
795 2
                $queryBuilder->setProjectionExpression($this->projectionExpression->parse($columns));
796
            }
797
        }
798
799 92
        if (!empty($this->lastEvaluatedKey)) {
800 15
            $queryBuilder->setExclusiveStartKey($this->lastEvaluatedKey);
801
        }
802
803
        $queryBuilder
804 92
            ->setExpressionAttributeNames($this->expressionAttributeNames->all())
805 92
            ->setExpressionAttributeValues($this->expressionAttributeValues->all());
806
807 92
        $raw = new RawDynamoDbQuery($op, $queryBuilder->prepare($this->client)->query);
808
809 92
        if ($this->decorator) {
810 4
            call_user_func($this->decorator, $raw);
811
        }
812
813 92
        return $raw;
814
    }
815
816
    /**
817
     * @return Analyzer
818
     */
819 97
    protected function getConditionAnalyzer()
820
    {
821 97
        return with(new Analyzer)
822 97
            ->on($this->model)
823 97
            ->withIndex($this->index)
824 97
            ->analyze($this->wheres);
825
    }
826
827 40
    protected function isMultipleIds($id)
828
    {
829 40
        $keys = collect($this->model->getKeyNames());
830
831
        // could be ['id' => 'foo'], ['id1' => 'foo', 'id2' => 'bar']
832
        $single = $keys->first(function ($name) use ($id) {
833 40
            return !isset($id[$name]);
834 40
        }) === null;
835
836 40
        if ($single) {
837 22
            return false;
838
        }
839
840
        // could be ['foo', 'bar'], [['id1' => 'foo', 'id2' => 'bar'], ...]
841 18
        return $this->model->hasCompositeKey() ? is_array(H::array_first($id)) : is_array($id);
842
    }
843
844
    /**
845
     * @return DynamoDbModel
846
     */
847 88
    public function getModel()
848
    {
849 88
        return $this->model;
850
    }
851
852
    /**
853
     * @return \Aws\DynamoDb\DynamoDbClient
854
     */
855
    public function getClient()
856
    {
857
        return $this->client;
858
    }
859
860
    /**
861
     * Register a new global scope.
862
     *
863
     * @param  string  $identifier
864
     * @param  \Illuminate\Database\Eloquent\Scope|\Closure  $scope
865
     * @return $this
866
     */
867 7
    public function withGlobalScope($identifier, $scope)
868
    {
869 7
        $this->scopes[$identifier] = $scope;
870
871 7
        if (method_exists($scope, 'extend')) {
872
            $scope->extend($this);
873
        }
874
875 7
        return $this;
876
    }
877
878
    /**
879
     * Remove a registered global scope.
880
     *
881
     * @param  \Illuminate\Database\Eloquent\Scope|string  $scope
882
     * @return $this
883
     */
884 3
    public function withoutGlobalScope($scope)
885
    {
886 3
        if (! is_string($scope)) {
887
            $scope = get_class($scope);
888
        }
889
890 3
        unset($this->scopes[$scope]);
891
892 3
        $this->removedScopes[] = $scope;
893
894 3
        return $this;
895
    }
896
897
    /**
898
     * Remove all or passed registered global scopes.
899
     *
900
     * @param  array|null  $scopes
901
     * @return $this
902
     */
903 5
    public function withoutGlobalScopes(array $scopes = null)
904
    {
905 5
        if (is_array($scopes)) {
906
            foreach ($scopes as $scope) {
907
                $this->withoutGlobalScope($scope);
908
            }
909
        } else {
910 5
            $this->scopes = [];
911
        }
912
913 5
        return $this;
914
    }
915
916
    /**
917
     * Get an array of global scopes that were removed from the query.
918
     *
919
     * @return array
920
     */
921
    public function removedScopes()
922
    {
923
        return $this->removedScopes;
924
    }
925
926
    /**
927
     * Apply the scopes to the Eloquent builder instance and return it.
928
     *
929
     * @return DynamoDbQueryBuilder
930
     */
931 92
    public function applyScopes()
932
    {
933 92
        if (! $this->scopes) {
934 91
            return $this;
935
        }
936
937 3
        $builder = $this;
938
939 3
        foreach ($builder->scopes as $identifier => $scope) {
940 3
            if (! isset($builder->scopes[$identifier])) {
941
                continue;
942
            }
943
944
            $builder->callScope(function (DynamoDbQueryBuilder $builder) use ($scope) {
945
                // If the scope is a Closure we will just go ahead and call the scope with the
946
                // builder instance. The "callScope" method will properly group the clauses
947
                // that are added to this query so "where" clauses maintain proper logic.
948 3
                if ($scope instanceof Closure) {
949 3
                    $scope($builder);
950
                }
951
952
                // If the scope is a scope object, we will call the apply method on this scope
953
                // passing in the builder and the model instance. After we run all of these
954
                // scopes we will return back the builder instance to the outside caller.
955 3
                if ($scope instanceof Scope) {
956
                    throw new NotSupportedException('Scope object is not yet supported');
957
                }
958 3
            });
959
960 3
            $builder->withoutGlobalScope($identifier);
961
        }
962
963 3
        return $builder;
964
    }
965
966
    /**
967
     * Apply the given scope on the current builder instance.
968
     *
969
     * @param  callable  $scope
970
     * @param  array  $parameters
971
     * @return mixed
972
     */
973 7
    protected function callScope(callable $scope, $parameters = [])
974
    {
975 7
        array_unshift($parameters, $this);
976
977
        // $query = $this->getQuery();
978
979
        // // We will keep track of how many wheres are on the query before running the
980
        // // scope so that we can properly group the added scope constraints in the
981
        // // query as their own isolated nested where statement and avoid issues.
982
        // $originalWhereCount = is_null($query->wheres)
983
        //             ? 0 : count($query->wheres);
984
985 7
        $result = $scope(...array_values($parameters)) ?: $this;
986
987
        // if (count((array) $query->wheres) > $originalWhereCount) {
988
        //     $this->addNewWheresWithinGroup($query, $originalWhereCount);
989
        // }
990
991 7
        return $result;
992
    }
993
994
    /**
995
     * Dynamically handle calls into the query instance.
996
     *
997
     * @param  string  $method
998
     * @param  array  $parameters
999
     * @return mixed
1000
     */
1001 7
    public function __call($method, $parameters)
1002
    {
1003 7
        if (method_exists($this->model, $scope = 'scope'.ucfirst($method))) {
1004 5
            return $this->callScope([$this->model, $scope], $parameters);
1005
        }
1006
1007 2
        return $this;
1008
    }
1009
}
1010