-
Notifications
You must be signed in to change notification settings - Fork 0
/
SearchManager.php
277 lines (235 loc) · 9.95 KB
/
SearchManager.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
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
<?php
/*
* This file is part of the Klipper package.
*
* (c) François Pluchino <francois.pluchino@klipper.dev>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Klipper\Component\Search;
use Doctrine\ORM\EntityRepository;
use Doctrine\ORM\QueryBuilder;
use Doctrine\ORM\Tools\Pagination\Paginator;
use Doctrine\Persistence\ManagerRegistry;
use Klipper\Component\DoctrineExtensionsExtra\Filterable\RequestFilterableQuery;
use Klipper\Component\DoctrineExtensionsExtra\Model\Traits\TranslatableInterface;
use Klipper\Component\DoctrineExtensionsExtra\Pagination\RequestPaginationQuery;
use Klipper\Component\DoctrineExtensionsExtra\Sortable\RequestSortableQuery;
use Klipper\Component\DoctrineExtensionsExtra\Util\QueryUtil;
use Klipper\Component\Metadata\MetadataContexts;
use Klipper\Component\Metadata\MetadataManagerInterface;
use Klipper\Component\Metadata\ObjectMetadataInterface;
use Klipper\Component\Search\Exception\InvalidArgumentException;
use Klipper\Component\Security\Organizational\OrganizationalContextInterface;
use Klipper\Component\Security\Permission\PermissionManagerInterface;
use Klipper\Component\Security\Permission\PermVote;
use Symfony\Component\Security\Core\Authorization\AuthorizationCheckerInterface;
/**
* @author François Pluchino <francois.pluchino@klipper.dev>
*/
class SearchManager implements SearchManagerInterface
{
protected MetadataManagerInterface $metadataManager;
protected PermissionManagerInterface $permissionManager;
protected ManagerRegistry $registry;
protected AuthorizationCheckerInterface $authChecker;
protected RequestPaginationQuery $requestPagination;
protected RequestFilterableQuery $requestFilterable;
protected RequestSortableQuery $requestSortable;
protected ?OrganizationalContextInterface $organizationalContext;
/**
* @var null|string[]
*/
protected ?array $cacheObjects = null;
/**
* @param MetadataManagerInterface $metadataManager The metadata manager
* @param PermissionManagerInterface $permissionManager The permission manager
* @param ManagerRegistry $registry The doctrine registry
* @param AuthorizationCheckerInterface $authChecker The authorization checker
* @param RequestPaginationQuery $requestPagination The request pagination query
* @param RequestFilterableQuery $requestFilterable The request filterable query
* @param RequestSortableQuery $requestSortable The request sortable query
* @param null|OrganizationalContextInterface $organizationalContext The organizational context
*/
public function __construct(
MetadataManagerInterface $metadataManager,
PermissionManagerInterface $permissionManager,
ManagerRegistry $registry,
AuthorizationCheckerInterface $authChecker,
RequestPaginationQuery $requestPagination,
RequestFilterableQuery $requestFilterable,
RequestSortableQuery $requestSortable,
?OrganizationalContextInterface $organizationalContext
) {
$this->metadataManager = $metadataManager;
$this->permissionManager = $permissionManager;
$this->registry = $registry;
$this->authChecker = $authChecker;
$this->requestPagination = $requestPagination;
$this->requestFilterable = $requestFilterable;
$this->requestSortable = $requestSortable;
$this->organizationalContext = $organizationalContext;
}
public function searchByObject(string $object, string $query, array $queryFields = []): SearchResultInterface
{
$results = $this->search($query, [$object], $queryFields);
if (!$results->hasObject($object)) {
throw new InvalidArgumentException(sprintf('The "%s" object doesn\'t exist', $object));
}
return $results->getObject($object);
}
public function search(string $query, array $objects = [], array $queryFields = []): SearchResultsInterface
{
$words = empty($query) ? [] : array_map('trim', explode(' ', $query));
$lockPage = 1 === \count($objects);
$objects = $this->validateObjects($objects);
$results = [];
foreach ($objects as $object => $class) {
$results[$object] = $this->searchObject($object, $class, $words, $lockPage, $queryFields);
}
return new SearchResults($results);
}
/**
* Search in object.
*
* @param string $object The object name
* @param string $class The class name
* @param string[] $words The words
* @param bool $lockPage Check if the request is locked on first page
* @param string[] $queryFields The query fields
*
* @throws
*/
protected function searchObject(string $object, string $class, array $words, bool $lockPage, array $queryFields = []): SearchResult
{
/** @var EntityRepository $repo */
$repo = $this->registry->getRepository($class);
$alias = '_'.$object;
$total = 0;
$results = [];
$page = 1;
$pages = 1;
if (!empty($words)) {
$qb = $repo->createQueryBuilder($alias);
$this->injectFilter($qb, $class, $alias, $words, $queryFields);
$query = $qb->getQuery();
$this->requestPagination->paginate($query, $lockPage);
$this->requestSortable->sort($query);
if ($lockPage) {
$this->requestFilterable->filter($query);
}
if (\in_array(TranslatableInterface::class, class_implements($class), true)) {
QueryUtil::translateQuery($query);
}
$paginator = new Paginator($query);
$total = $paginator->count();
$limit = $query->getMaxResults();
if ($total > 0) {
$results = $paginator->getIterator()->getArrayCopy();
$page = (int) $query->getHint(RequestPaginationQuery::HINT_PAGE_NUMBER);
$pages = (int) ceil($total / $query->getMaxResults());
}
} else {
$query = $repo->createQueryBuilder($alias)->getQuery();
$this->requestPagination->paginate($query, $lockPage);
$limit = $query->getMaxResults();
}
return new SearchResult(
$object,
$results,
$page,
$limit,
$pages,
$total
);
}
/**
* Validate the objects.
*
* @param string[] $objects The objects
*
* @return string[]
*/
protected function validateObjects(array $objects): array
{
$validObjects = $this->getObjectClasses();
$valid = [];
if (empty($objects)) {
$valid = $validObjects;
} else {
foreach ($objects as $object) {
if (isset($validObjects[$object])) {
$valid[$object] = $validObjects[$object];
}
}
}
return $valid;
}
/**
* Get the objects.
*
* @return string[]
*/
protected function getObjectClasses(): array
{
if (null === $this->cacheObjects) {
$this->cacheObjects = [];
foreach ($this->metadataManager->all() as $metadata) {
if ($metadata->isPublic() && $metadata->isSearchable()
&& $this->isValidContext($metadata)
&& $this->authChecker->isGranted(new PermVote('view'), $metadata->getClass())) {
$config = $this->permissionManager->hasConfig($metadata->getClass())
? $this->permissionManager->getConfig($metadata->getClass())
: null;
if ($config && null === $config->getMaster()) {
$this->cacheObjects[$metadata->getName()] = $metadata->getClass();
}
}
}
}
return $this->cacheObjects;
}
/**
* Inject the filter in the query builder.
*
* @param QueryBuilder $qb The query builder for filter
* @param string $class The class name
* @param string $alias The alias
* @param string[] $words The words
* @param string[] $queryFields The query fields
*/
private function injectFilter(QueryBuilder $qb, string $class, string $alias, array $words, array $queryFields = []): QueryBuilder
{
$fields = $this->metadataManager->get($class)->getFields();
$filter = '';
foreach ($fields as $fieldMeta) {
$field = $alias.'.'.$fieldMeta->getField();
if ($fieldMeta->isPublic() && $fieldMeta->isSearchable()
&& (empty($queryFields) || \in_array($fieldMeta->getName(), $queryFields, true))
) {
$filter .= '' === $filter ? '(' : ' OR (';
foreach ($words as $i => $word) {
$key = 'search_'.str_replace(['.'], '_', $field).'_'.($i + 1);
$qb->setParameter($key, '%'.$word.'%');
$filter .= 0 === $i ? '' : ' AND ';
$filter .= 'UNACCENT(LOWER('.$field.')) LIKE UNACCENT(LOWER(:'.$key.'))';
}
$filter .= ')';
}
}
return $qb->andWhere($filter);
}
/**
* Check if the metadata is compatible with organizational context.
*
* @param ObjectMetadataInterface $metadata The object metadata
*/
private function isValidContext(ObjectMetadataInterface $metadata): bool
{
if ($this->organizationalContext && $this->organizationalContext->isOrganization()) {
return \in_array(MetadataContexts::ORGANIZATION, $metadata->getAvailableContexts(), true);
}
return \in_array(MetadataContexts::USER, $metadata->getAvailableContexts(), true);
}
}