Completed
Pull Request — master (#128)
by Bao
08:01
created

DynamoDbCollection::__construct()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 9

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 7
CRAP Score 2

Importance

Changes 0
Metric Value
dl 0
loc 9
ccs 7
cts 7
cp 1
rs 9.9666
c 0
b 0
f 0
cc 2
nc 2
nop 3
crap 2
1
<?php
2
3
namespace BaoPham\DynamoDb;
4
5
use Illuminate\Database\Eloquent\Collection;
6
7
class DynamoDbCollection extends Collection
8
{
9
    protected $lastEvaluatedKey = null;
10
    protected $conditionIndexKeys = null;
11
    protected $model = null;
12
13 90
    public function __construct(array $models = [], $lastEvaluatedKey = null, $conditionIndexKeys = null)
14
    {
15 90
        parent::__construct($models);
16 90
        $this->lastEvaluatedKey = $lastEvaluatedKey;
17 90
        $this->conditionIndexKeys = $conditionIndexKeys;
18
19 90
        if (!$this->isEmpty()) {
20 86
            $class = get_class($this->first());
21 86
            $this->model = new $class;
22
        }
23 90
    }
24
25 4
    public function getLastEvaluatedKey()
26
    {
27 4
        if (!empty($this->lastEvaluatedKey)) {
28 4
            return $this->lastEvaluatedKey;
29
        }
30
31
        $after = $this->last();
32
33
        if (empty($after)) {
34
            return null;
35
        }
36
37
        $afterKey = $after->getKeys();
38
39
        if ($this->conditionIndexKeys) {
40
            $columns = array_values($conditionIndexKeys['keysInfo']);
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $conditionIndexKeys seems to be never defined.
Loading history...
41
            foreach ($columns as $column) {
42
                $afterKey[$column] = $after->getAttribute($column);
43
            }
44
        }
45
46
        return $this->model->unmarshalValue($this->getDynamoDbKey($afterKey));
47
    }
48
49
    /**
50
     * Return key for DynamoDb query.
51
     *
52
     * @param array|null $modelKeys
53
     * @return array
54
     *
55
     * e.g.
56
     * [
57
     *   'id' => ['S' => 'foo'],
58
     * ]
59
     *
60
     * or
61
     *
62
     * [
63
     *   'id' => ['S' => 'foo'],
64
     *   'id2' => ['S' => 'bar'],
65
     * ]
66
     */
67
    protected function getDynamoDbKey($modelKeys = null)
68
    {
69
        $modelKeys = $modelKeys ?: $this->model->getKeys();
70
71
        $keys = [];
72
73
        foreach ($modelKeys as $key => $value) {
74
            if (is_null($value)) {
75
                continue;
76
            }
77
            $keys[$key] = $this->model->marshalValue($value);
78
        }
79
80
        return $keys;
81
    }
82
}
83