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

DynamoDbCollection   A

Complexity

Total Complexity 11

Size/Duplication

Total Lines 74
Duplicated Lines 0 %

Test Coverage

Coverage 39.29%

Importance

Changes 0
Metric Value
wmc 11
dl 0
loc 74
ccs 11
cts 28
cp 0.3929
rs 10
c 0
b 0
f 0

3 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 9 2
A getDynamoDbKey() 0 14 4
A getLastEvaluatedKey() 0 22 5
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