1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace LaravelFreelancerNL\FluentAQL\Traits; |
4
|
|
|
|
5
|
|
|
use LaravelFreelancerNL\FluentAQL\Expressions\PredicateExpression; |
6
|
|
|
|
7
|
|
|
/** |
8
|
|
|
* Trait hasFunctions. |
9
|
|
|
* |
10
|
|
|
* AQL Function API calls. |
11
|
|
|
*/ |
12
|
|
|
trait CompilesPredicates |
13
|
|
|
{ |
14
|
|
|
/** |
15
|
|
|
* @param PredicateExpression|array $predicates |
16
|
|
|
* @return string |
17
|
|
|
*/ |
18
|
4 |
|
public function compilePredicates($predicates) |
19
|
|
|
{ |
20
|
4 |
|
if (! is_array($predicates)) { |
21
|
|
|
$predicates = [$predicates]; |
22
|
|
|
} |
23
|
|
|
|
24
|
4 |
|
$compiledPredicates = []; |
25
|
4 |
|
for ($i = 0; $i < count($predicates); $i++) { |
|
|
|
|
26
|
4 |
|
if ($predicates[$i] instanceof PredicateExpression) { |
27
|
4 |
|
$compiledPredicates[] = $this->compilePredicate($predicates[$i], $i); |
28
|
|
|
} |
29
|
|
|
|
30
|
4 |
|
if (is_array($predicates[$i])) { |
31
|
|
|
$compiledPredicates[] = $this->compilePredicateGroup($predicates[$i], $i); |
32
|
|
|
} |
33
|
|
|
} |
34
|
|
|
|
35
|
4 |
|
return implode(' ', $compiledPredicates); |
36
|
|
|
} |
37
|
|
|
|
38
|
4 |
|
protected function compilePredicate(PredicateExpression $predicate, $position = 0) |
39
|
|
|
{ |
40
|
4 |
|
$compiledPredicate = ''; |
41
|
4 |
|
if ($position > 0) { |
42
|
|
|
$compiledPredicate = $predicate->logicalOperator . ' ' ; |
43
|
|
|
} |
44
|
4 |
|
return $compiledPredicate . $predicate->compile($this); |
45
|
|
|
} |
46
|
|
|
|
47
|
|
|
protected function compilePredicateGroup(array $predicates, $position = 0) |
48
|
|
|
{ |
49
|
|
|
$compiledPredicates = []; |
50
|
|
|
$logicalOperator = ''; |
51
|
|
|
if ($predicates[0] instanceof PredicateExpression) { |
52
|
|
|
$logicalOperator = $predicates[0]->logicalOperator; |
53
|
|
|
} |
54
|
|
|
for ($i = 0; $i < count($predicates); $i++) { |
|
|
|
|
55
|
|
|
$compiledPredicates[] = $this->compilePredicate($predicates[$i], $i); |
56
|
|
|
} |
57
|
|
|
|
58
|
|
|
$groupCompilation = ''; |
59
|
|
|
if ($position > 0) { |
60
|
|
|
$groupCompilation = $logicalOperator . ' '; |
61
|
|
|
} |
62
|
|
|
return $groupCompilation . '(' . implode(' ', $compiledPredicates) . ')'; |
63
|
|
|
} |
64
|
|
|
} |
65
|
|
|
|
If the size of the collection does not change during the iteration, it is generally a good practice to compute it beforehand, and not on each iteration: