1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
declare(strict_types=1); |
4
|
|
|
|
5
|
|
|
namespace LaravelFreelancerNL\FluentAQL\Traits; |
6
|
|
|
|
7
|
|
|
use LaravelFreelancerNL\FluentAQL\Expressions\PredicateExpression; |
8
|
|
|
|
9
|
|
|
trait CompilesPredicates |
10
|
|
|
{ |
11
|
|
|
/** |
12
|
|
|
* @param array<mixed>|PredicateExpression $predicates |
13
|
|
|
*/ |
14
|
16 |
|
public function compilePredicates( |
15
|
|
|
array|PredicateExpression $predicates |
16
|
|
|
): string { |
17
|
16 |
|
if (! is_array($predicates)) { |
|
|
|
|
18
|
1 |
|
$predicates = [$predicates]; |
19
|
|
|
} |
20
|
|
|
|
21
|
16 |
|
$compiledPredicates = []; |
22
|
16 |
|
for ($i = 0; $i < count($predicates); $i++) { |
|
|
|
|
23
|
16 |
|
if ($predicates[$i] instanceof PredicateExpression) { |
24
|
16 |
|
$compiledPredicates[] = $this->compilePredicate($predicates[$i], $i); |
25
|
|
|
} |
26
|
|
|
|
27
|
16 |
|
if (is_array($predicates[$i])) { |
28
|
2 |
|
$compiledPredicates[] = $this->compilePredicateGroup($predicates[$i], $i); |
29
|
|
|
} |
30
|
|
|
} |
31
|
|
|
|
32
|
16 |
|
return implode(' ', $compiledPredicates); |
33
|
|
|
} |
34
|
|
|
|
35
|
16 |
|
protected function compilePredicate(PredicateExpression $predicate, int $position = 0): string |
36
|
|
|
{ |
37
|
16 |
|
$compiledPredicate = ''; |
38
|
16 |
|
if ($position > 0) { |
39
|
7 |
|
$compiledPredicate = $predicate->logicalOperator . ' ' ; |
40
|
|
|
} |
41
|
16 |
|
return $compiledPredicate . $predicate->compile($this); |
42
|
|
|
} |
43
|
|
|
|
44
|
|
|
/** |
45
|
|
|
* @param array<mixed> $predicates |
46
|
|
|
* @param int $position |
47
|
|
|
* @return string |
48
|
|
|
*/ |
49
|
2 |
|
protected function compilePredicateGroup( |
50
|
|
|
array $predicates, |
51
|
|
|
int $position = 0 |
52
|
|
|
): string { |
53
|
2 |
|
$compiledPredicates = []; |
54
|
2 |
|
$logicalOperator = ''; |
55
|
2 |
|
if ($predicates[0] instanceof PredicateExpression) { |
56
|
2 |
|
$logicalOperator = $predicates[0]->logicalOperator; |
57
|
|
|
} |
58
|
2 |
|
for ($i = 0; $i < count($predicates); $i++) { |
|
|
|
|
59
|
2 |
|
if ($predicates[$i] instanceof PredicateExpression) { |
60
|
2 |
|
$compiledPredicates[] = $this->compilePredicate($predicates[$i], $i); |
61
|
|
|
} |
62
|
|
|
} |
63
|
|
|
|
64
|
2 |
|
$groupCompilation = ''; |
65
|
2 |
|
if ($position > 0) { |
66
|
1 |
|
$groupCompilation = $logicalOperator . ' '; |
67
|
|
|
} |
68
|
2 |
|
return $groupCompilation . '(' . implode(' ', $compiledPredicates) . ')'; |
69
|
|
|
} |
70
|
|
|
} |
71
|
|
|
|