-
Notifications
You must be signed in to change notification settings - Fork 25
/
Finder.php
135 lines (112 loc) · 2.68 KB
/
Finder.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
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
<?php
namespace Paknahad\JsonApiBundle\Helper\Filter;
use Doctrine\ORM\QueryBuilder;
use Paknahad\JsonApiBundle\Helper\FieldManager;
use Paknahad\JsonApiBundle\Helper\Sorter;
use Symfony\Component\HttpFoundation\Request;
/**
* Class Finder.
*/
class Finder implements FinderInterface
{
/**
* @var QueryBuilder
*/
protected $query;
/**
* @var Request
*/
protected $request;
/**
* @var FieldManager
*/
protected $fieldManager;
/**
* @var Sorter
*/
protected $sorter;
/**
* Finder constructor.
*/
public function __construct(Sorter $sorter)
{
$this->sorter = $sorter;
}
/**
* {@inheritdoc}
*/
public function setRequest(Request $request): void
{
$this->request = $request;
}
/**
* {@inheritdoc}
*/
public function setQuery(QueryBuilder $query): void
{
$this->query = $query;
}
/**
* {@inheritdoc}
*/
public function setFieldManager(FieldManager $fieldManager): void
{
$this->fieldManager = $fieldManager;
}
/**
* {@inheritdoc}
*/
public function filterQuery(): void
{
$filters = $this->request->get('filter', []);
foreach ($filters as $field => $value) {
$this->setCondition($field, $value);
}
}
/**
* {@inheritdoc}
*/
public function sortQuery(): void
{
$this->sorter->handleQuery($this->query, $this->request, $this->fieldManager);
}
/**
* @throws \Doctrine\ORM\EntityNotFoundException
*/
protected function setCondition(string $field, string $value): void
{
$fieldMetaData = $this->fieldManager->addField($field);
$this->query->andWhere(sprintf(
'%s %s %s',
$this->fieldManager->getQueryFieldName($field),
$this->getOperator($fieldMetaData, $value),
$this->setValue($value)
));
}
protected function getOperator(array $fieldMetadata, string &$value): string
{
if ('null' === strtolower($value)) {
$value = null;
return 'IS NULL';
}
if ('string' === $fieldMetadata['metadata']['type'] && false !== strpos($value, '%')) {
return 'LIKE';
}
return '=';
}
/**
* Set value & return that parameter name.
*
* @param mixed $value
*/
protected function setValue($value): string
{
static $iterator = 1;
if (null === $value) {
return '';
}
$paramName = ':P'.$iterator++;
$this->query->setParameter($paramName, $value);
return $paramName;
}
}