-
-
Notifications
You must be signed in to change notification settings - Fork 1.3k
/
Copy pathRetrieveAutocompleteItemsAction.php
225 lines (185 loc) · 8.26 KB
/
RetrieveAutocompleteItemsAction.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
<?php
declare(strict_types=1);
/*
* This file is part of the Sonata Project package.
*
* (c) Thomas Rabaix <[email protected]>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Sonata\AdminBundle\Action;
use Sonata\AdminBundle\Admin\AdminInterface;
use Sonata\AdminBundle\Admin\FieldDescriptionInterface;
use Sonata\AdminBundle\Admin\Pool;
use Sonata\AdminBundle\Filter\FilterInterface;
use Symfony\Component\Form\Form;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Security\Core\Exception\AccessDeniedException;
final class RetrieveAutocompleteItemsAction
{
/**
* @var Pool
*/
private $pool;
public function __construct(Pool $pool)
{
$this->pool = $pool;
}
/**
* Retrieve list of items for autocomplete form field.
*
* @throws \RuntimeException
* @throws AccessDeniedException
*/
public function __invoke(Request $request): JsonResponse
{
$admin = $this->pool->getInstance($request->get('admin_code'));
$admin->setRequest($request);
$context = $request->get('_context', '');
if ('filter' === $context) {
$admin->checkAccess('list');
} elseif (!$admin->hasAccess('create') && !$admin->hasAccess('edit')) {
throw new AccessDeniedException();
}
// subject will be empty to avoid unnecessary database requests and keep autocomplete function fast
$admin->setSubject($admin->getNewInstance());
if ('filter' === $context) {
// filter
$fieldDescription = $this->retrieveFilterFieldDescription($admin, $request->get('field'));
$filterAutocomplete = $admin->getDatagrid()->getFilter($fieldDescription->getName());
$property = $filterAutocomplete->getFieldOption('property');
$callback = $filterAutocomplete->getFieldOption('callback');
$minimumInputLength = $filterAutocomplete->getFieldOption('minimum_input_length', 3);
$itemsPerPage = $filterAutocomplete->getFieldOption('items_per_page', 10);
$reqParamPageNumber = $filterAutocomplete->getFieldOption('req_param_name_page_number', '_page');
$toStringCallback = $filterAutocomplete->getFieldOption('to_string_callback');
$targetAdminAccessAction = $filterAutocomplete->getFieldOption('target_admin_access_action', 'list');
} else {
// create/edit form
$fieldDescription = $this->retrieveFormFieldDescription($admin, $request->get('field'));
$formAutocomplete = $admin->getForm()->get($fieldDescription->getName());
$formAutocompleteConfig = $formAutocomplete->getConfig();
if ($formAutocompleteConfig->getAttribute('disabled')) {
throw new AccessDeniedException(
'Autocomplete list can`t be retrieved because the form element is disabled or read_only.'
);
}
$property = $formAutocompleteConfig->getAttribute('property');
$callback = $formAutocompleteConfig->getAttribute('callback');
$minimumInputLength = $formAutocompleteConfig->getAttribute('minimum_input_length');
$itemsPerPage = $formAutocompleteConfig->getAttribute('items_per_page');
$reqParamPageNumber = $formAutocompleteConfig->getAttribute('req_param_name_page_number');
$toStringCallback = $formAutocompleteConfig->getAttribute('to_string_callback');
$targetAdminAccessAction = $formAutocompleteConfig->getAttribute('target_admin_access_action');
}
$searchText = $request->get('q');
$targetAdmin = $fieldDescription->getAssociationAdmin();
// check user permission
$targetAdmin->checkAccess($targetAdminAccessAction);
if (mb_strlen($searchText, 'UTF-8') < $minimumInputLength) {
return new JsonResponse(['status' => 'KO', 'message' => 'Too short search string.'], Response::HTTP_FORBIDDEN);
}
$targetAdmin->setFilterPersister(null);
$datagrid = $targetAdmin->getDatagrid();
if (null !== $callback) {
if (!\is_callable($callback)) {
throw new \RuntimeException('Callback does not contain callable function.');
}
$callback($targetAdmin, $property, $searchText);
} else {
if (\is_array($property)) {
// multiple properties
foreach ($property as $prop) {
if (!$datagrid->hasFilter($prop)) {
throw new \RuntimeException(sprintf(
'To retrieve autocomplete items,'
.' you should add filter "%s" to "%s" in configureDatagridFilters() method.',
$prop,
\get_class($targetAdmin)
));
}
$filter = $datagrid->getFilter($prop);
$filter->setCondition(FilterInterface::CONDITION_OR);
$datagrid->setValue($filter->getFormName(), null, $searchText);
}
} else {
if (!$datagrid->hasFilter($property)) {
throw new \RuntimeException(sprintf(
'To retrieve autocomplete items,'
.' you should add filter "%s" to "%s" in configureDatagridFilters() method.',
$property,
\get_class($targetAdmin)
));
}
$datagrid->setValue($datagrid->getFilter($property)->getFormName(), null, $searchText);
}
}
$datagrid->setValue('_per_page', null, $itemsPerPage);
$datagrid->setValue('_page', null, $request->query->get($reqParamPageNumber, 1));
$datagrid->buildPager();
$pager = $datagrid->getPager();
$items = [];
$results = $pager->getResults();
foreach ($results as $model) {
if (null !== $toStringCallback) {
if (!\is_callable($toStringCallback)) {
throw new \RuntimeException('Option "to_string_callback" does not contain callable function.');
}
$label = $toStringCallback($model, $property);
} else {
$resultMetadata = $targetAdmin->getObjectMetadata($model);
$label = $resultMetadata->getTitle();
}
$items[] = [
'id' => $admin->id($model),
'label' => $label,
];
}
return new JsonResponse([
'status' => 'OK',
'more' => !$pager->isLastPage(),
'items' => $items,
]);
}
/**
* Retrieve the filter field description given by field name.
*
* @throws \RuntimeException
*/
private function retrieveFilterFieldDescription(
AdminInterface $admin,
string $field
): FieldDescriptionInterface {
$admin->getFilterFieldDescriptions();
$fieldDescription = $admin->getFilterFieldDescription($field);
if (!$fieldDescription) {
throw new \RuntimeException(sprintf('The field "%s" does not exist.', $field));
}
if (null === $fieldDescription->getTargetEntity()) {
throw new \RuntimeException(sprintf('No associated entity with field "%s".', $field));
}
return $fieldDescription;
}
/**
* Retrieve the form field description given by field name.
*
* @throws \RuntimeException
*/
private function retrieveFormFieldDescription(
AdminInterface $admin,
string $field
): FieldDescriptionInterface {
$admin->getFormFieldDescriptions();
$fieldDescription = $admin->getFormFieldDescription($field);
if (!$fieldDescription) {
throw new \RuntimeException(sprintf('The field "%s" does not exist.', $field));
}
if (null === $fieldDescription->getTargetEntity()) {
throw new \RuntimeException(sprintf('No associated entity with field "%s".', $field));
}
return $fieldDescription;
}
}