/
FilterWhereParser.php
101 lines (82 loc) · 2.95 KB
/
FilterWhereParser.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
<?php
namespace Pushword\Core\Repository;
use Doctrine\ORM\Query\Expr\Andx;
use Doctrine\ORM\Query\Expr\Orx;
use Doctrine\ORM\QueryBuilder;
/**
* Eg:
* ['title', 'LIKE' '%this%'] => works
* [['title', 'LIKE' '%this%']] => works
* [['title', 'LIKE' '%this%'], 'OR', ['title', 'LIKE' '%that%']] => works
* [[['title', 'LIKE' '%this%'], ['title', 'LIKE' '%this%']], 'OR', ['title', 'LIKE' '%that%']] => works
*/
class FilterWhereParser
{
/**
* @param array<mixed> $where
*/
public function __construct(
private readonly QueryBuilder $queryBuilder,
private array $where
) {
}
public function parseAndAdd(): QueryBuilder
{
if ([] === $this->where) {
return $this->queryBuilder;
}
// Normalize array [']
if (! isset($this->where[0]) || ! \is_array($this->where[0])) { // eg : ['key' => 'test'...] or ['test', ...]
$this->where = [$this->where];
}
return $this->queryBuilder->andWhere($this->retrieveFrom($this->where));
}
/**
* @param array<mixed> $where
*/
private function containsSubQuery(array $where): bool
{
return \is_array(array_values($where)[0] ?? throw new \Exception());
}
/**
* @param array<mixed> $where
*/
private function retrieveFrom(array $where): Andx|Orx
{
$compose = \in_array('OR', $where, true) ? $this->queryBuilder->expr()->orX() : $this->queryBuilder->expr()->andX();
foreach ($where as $singleWhere) {
if ('OR' === $singleWhere) {
continue;
}
if (! \is_array($singleWhere)) {
throw new \Exception('malformated where params');
}
if ($this->containsSubQuery($singleWhere)) {
$compose->add($this->retrieveFrom($singleWhere));
continue;
}
$compose->add($this->retrieveExpressionFrom($singleWhere));
}
return $compose;
}
/**
* @param array<mixed> $whereRow
*/
private function retrieveExpressionFrom(array $whereRow): string
{
$paramKey = 'm'.md5('a'.random_int(0, mt_getrandmax()));
$prefix = $whereRow['key_prefix'] ?? $whereRow[4] ?? 'p.';
$key = $whereRow['key'] ?? $whereRow[0] ?? throw new \Exception('key was forgotten');
$operator = $whereRow['operator'] ?? $whereRow[1] ?? throw new \Exception('operator was forgotten');
$sqlValue = 'IN' === $operator ? '( :'.$paramKey.')' : ' :'.$paramKey;
$value = $whereRow['value'] ?? $whereRow[2];
if (null === $value) {
if (! \in_array($operator, ['IS', 'IS NOT'], true)) {
throw new \Exception('operator `'.$operator.'` forbidden for null value');
}
return $prefix.$key.' '.$operator.' NULL';
}
$this->queryBuilder->setParameter($paramKey, $value);
return $prefix.$key.' '.$operator.' '.$sqlValue;
}
}