-
-
Notifications
You must be signed in to change notification settings - Fork 1.3k
/
SearchHandler.php
94 lines (77 loc) · 2.73 KB
/
SearchHandler.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
<?php
declare(strict_types=1);
/*
* This file is part of the Sonata Project package.
*
* (c) Thomas Rabaix <thomas.rabaix@sonata-project.org>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Sonata\AdminBundle\Search;
use Sonata\AdminBundle\Admin\AdminInterface;
use Sonata\AdminBundle\Datagrid\PagerInterface;
use Sonata\AdminBundle\Datagrid\ProxyQueryInterface;
use Sonata\AdminBundle\Filter\FilterInterface;
/**
* @author Thomas Rabaix <thomas.rabaix@sonata-project.org>
*/
final class SearchHandler
{
/**
* @var array<string, bool>
*/
private array $adminsSearchConfig = [];
/**
* @throws \RuntimeException
*
* @phpstan-template T of object
* @phpstan-param AdminInterface<T> $admin
* @phpstan-return PagerInterface<ProxyQueryInterface<T>>|null
*/
public function search(AdminInterface $admin, string $term, int $page = 0, int $offset = 20): ?PagerInterface
{
// If the search is disabled for the whole admin, skip any further processing.
if (false === ($this->adminsSearchConfig[$admin->getCode()] ?? true)) {
return null;
}
$datagrid = $admin->getDatagrid();
$datagridValues = $datagrid->getValues();
$found = false;
$previousFilter = null;
foreach ($datagrid->getFilters() as $filter) {
$formName = $filter->getFormName();
if ($filter instanceof SearchableFilterInterface && $filter->isSearchEnabled()) {
if (null !== $previousFilter) {
$filter->setPreviousFilter($previousFilter);
}
$filter->setCondition(FilterInterface::CONDITION_OR);
$datagrid->setValue($formName, null, $term);
$found = true;
$previousFilter = $filter;
} elseif (isset($datagridValues[$formName])) {
// Remove any previously set filter that is not configured for the global search.
$datagrid->removeFilter($formName);
}
}
if (!$found) {
return null;
}
$datagrid->buildPager();
$pager = $datagrid->getPager();
$pager->setPage($page);
$pager->setMaxPerPage($offset);
$pager->init();
return $pager;
}
/**
* Sets whether the search must be enabled or not for the passed admin codes.
* Receives an array with the admin code as key and a boolean as value.
*
* @param array<string, bool> $adminsSearchConfig
*/
public function configureAdminSearch(array $adminsSearchConfig): void
{
$this->adminsSearchConfig = $adminsSearchConfig;
}
}