1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace Guillermoandrae\DynamoDb\Contract; |
4
|
|
|
|
5
|
|
|
use ErrorException; |
6
|
|
|
use Guillermoandrae\DynamoDb\Constant\Operators; |
7
|
|
|
|
8
|
|
|
abstract class AbstractFilterExpressionAwareOperation extends AbstractItemOperation |
9
|
|
|
{ |
10
|
|
|
use LimitAwareOperationTrait; |
11
|
|
|
|
12
|
|
|
/** |
13
|
|
|
* @var string The filter expression. |
14
|
|
|
*/ |
15
|
|
|
protected $filterExpression; |
16
|
|
|
|
17
|
|
|
/** |
18
|
|
|
* Registers the filter expression with this object. |
19
|
|
|
* |
20
|
|
|
* @param array $data The filter expression data. |
21
|
|
|
* @return AbstractFilterExpressionAwareOperation An implementation of this abstract. |
22
|
|
|
* @throws ErrorException |
23
|
|
|
*/ |
24
|
6 |
|
final public function setFilterExpression(array $data): AbstractFilterExpressionAwareOperation |
25
|
|
|
{ |
26
|
6 |
|
$filterExpressionArray = []; |
27
|
6 |
|
foreach ($data as $key => $options) { |
28
|
6 |
|
$filterExpressionArray[] = $this->parseExpression($options['operator'], $key); |
29
|
5 |
|
$this->addExpressionAttributeValue($key, $options['value']); |
30
|
|
|
} |
31
|
5 |
|
$this->filterExpression = implode(' and ', $filterExpressionArray); |
32
|
5 |
|
return $this; |
33
|
|
|
} |
34
|
|
|
|
35
|
|
|
/** |
36
|
|
|
* {@inheritDoc} |
37
|
|
|
*/ |
38
|
19 |
|
public function toArray(): array |
39
|
|
|
{ |
40
|
19 |
|
$query = parent::toArray(); |
41
|
19 |
|
if ($this->limit) { |
42
|
1 |
|
$query['Limit'] = $this->limit; |
43
|
|
|
} |
44
|
19 |
|
if ($this->filterExpression) { |
45
|
5 |
|
$query['FilterExpression'] = $this->filterExpression; |
46
|
|
|
} |
47
|
19 |
|
return $query; |
48
|
|
|
} |
49
|
|
|
|
50
|
|
|
/** |
51
|
|
|
* Uses the operator to build the filter expression. |
52
|
|
|
* |
53
|
|
|
* @param string $operator The request operator. |
54
|
|
|
* @param string $key The attribute key. |
55
|
|
|
* @return string The expression. |
56
|
|
|
* @throws ErrorException |
57
|
|
|
*/ |
58
|
9 |
|
protected function parseExpression(string $operator, string $key): string |
59
|
|
|
{ |
60
|
|
|
switch ($operator) { |
61
|
9 |
|
case Operators::BEGINS_WITH: |
62
|
1 |
|
return sprintf('begins_with(%s, :%s)', $key, $key); |
63
|
9 |
|
case Operators::CONTAINS: |
64
|
1 |
|
return sprintf('contains(%s, :%s)', $key, $key); |
65
|
9 |
|
case Operators::EQ: |
66
|
4 |
|
return sprintf('%s = :%s', $key, $key); |
67
|
7 |
|
case Operators::GT: |
68
|
1 |
|
return sprintf('%s > :%s', $key, $key); |
69
|
6 |
|
case Operators::GTE: |
70
|
3 |
|
return sprintf('%s >= :%s', $key, $key); |
71
|
3 |
|
case Operators::LT: |
72
|
1 |
|
return sprintf('%s < :%s', $key, $key); |
73
|
2 |
|
case Operators::LTE: |
74
|
1 |
|
return sprintf('%s <= :%s', $key, $key); |
75
|
|
|
default: |
76
|
1 |
|
throw new ErrorException('The provided operator is not supported.'); |
77
|
|
|
} |
78
|
|
|
} |
79
|
|
|
} |
80
|
|
|
|