-
-
Notifications
You must be signed in to change notification settings - Fork 1.1k
Expand file tree
/
Copy pathCollectionConfigurator.php
More file actions
268 lines (227 loc) · 13.8 KB
/
Copy pathCollectionConfigurator.php
File metadata and controls
268 lines (227 loc) · 13.8 KB
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
<?php
namespace EasyCorp\Bundle\EasyAdminBundle\Field\Configurator;
use Doctrine\ORM\PersistentCollection;
use EasyCorp\Bundle\EasyAdminBundle\Collection\FieldCollection;
use EasyCorp\Bundle\EasyAdminBundle\Config\Action;
use EasyCorp\Bundle\EasyAdminBundle\Config\Crud;
use EasyCorp\Bundle\EasyAdminBundle\Config\Option\EA;
use EasyCorp\Bundle\EasyAdminBundle\Context\AdminContext;
use EasyCorp\Bundle\EasyAdminBundle\Contracts\Field\FieldConfiguratorInterface;
use EasyCorp\Bundle\EasyAdminBundle\Contracts\Provider\AdminContextProviderInterface;
use EasyCorp\Bundle\EasyAdminBundle\Dto\EntityDto;
use EasyCorp\Bundle\EasyAdminBundle\Dto\FieldDto;
use EasyCorp\Bundle\EasyAdminBundle\Factory\ControllerFactory;
use EasyCorp\Bundle\EasyAdminBundle\Factory\EntityFactory;
use EasyCorp\Bundle\EasyAdminBundle\Factory\FieldFactory;
use EasyCorp\Bundle\EasyAdminBundle\Field\CollectionField;
use EasyCorp\Bundle\EasyAdminBundle\Form\Type\CrudFormType;
use Symfony\Component\Form\Extension\Core\Type\CountryType;
use Symfony\Component\Form\Extension\Core\Type\CurrencyType;
use Symfony\Component\Form\Extension\Core\Type\LanguageType;
use Symfony\Component\Form\Extension\Core\Type\LocaleType;
use Symfony\Component\Form\Extension\Core\Type\TimezoneType;
use Symfony\Component\HttpFoundation\RequestStack;
use function Symfony\Component\String\u;
/**
* @author Javier Eguiluz <javier.eguiluz@gmail.com>
*/
final readonly class CollectionConfigurator implements FieldConfiguratorInterface
{
public function __construct(
private RequestStack $requestStack,
private EntityFactory $entityFactory,
private ControllerFactory $controllerFactory,
private FieldFactory $fieldFactory,
private AdminContextProviderInterface $adminContextProvider,
) {
}
public function supports(FieldDto $field, EntityDto $entityDto): bool
{
return CollectionField::class === $field->getFieldFqcn();
}
public function configure(FieldDto $field, EntityDto $entityDto, AdminContext $context): void
{
if (null !== $entryTypeFqcn = $field->getCustomOptions()->get(CollectionField::OPTION_ENTRY_TYPE)) {
$field->setFormTypeOption('entry_type', $entryTypeFqcn);
}
$autocompletableFormTypes = [CountryType::class, CurrencyType::class, LanguageType::class, LocaleType::class, TimezoneType::class];
if (\in_array($entryTypeFqcn, $autocompletableFormTypes, true)) {
$field->setFormTypeOption('entry_options.attr.data-ea-widget', 'ea-autocomplete');
}
// the contents of this field are a collection of other fields, so it cannot be sorted
$field->setSortable(false);
$field->setFormTypeOptionIfNotSet('allow_add', $field->getCustomOptions()->get(CollectionField::OPTION_ALLOW_ADD));
$field->setFormTypeOptionIfNotSet('allow_delete', $field->getCustomOptions()->get(CollectionField::OPTION_ALLOW_DELETE));
$field->setFormTypeOptionIfNotSet('by_reference', false);
$field->setFormTypeOptionIfNotSet('delete_empty', true);
$field->setFormTypeOptionIfNotSet('prototype_name', '__'.u($field->getProperty())->replace('.', '_').'name__');
// TODO: check why this label (hidden by default) is not working properly
// (generated values are always the same for all elements)
$field->setFormTypeOptionIfNotSet('entry_options.label', $field->getCustomOptions()->get(CollectionField::OPTION_SHOW_ENTRY_LABEL));
// collection items range from a simple <input text> to a complex multi-field form
// the 'entryIsComplex' setting tells if the collection item is so complex that needs a special
// rendering not applied to simple collection items
if (null === $field->getCustomOption(CollectionField::OPTION_ENTRY_IS_COMPLEX)) {
$definesEntryType = null !== $entryTypeFqcn = $field->getCustomOption(CollectionField::OPTION_ENTRY_TYPE);
$isSymfonyCoreFormType = null !== u($entryTypeFqcn ?? '')->indexOf('Symfony\Component\Form\Extension\Core\Type');
$isComplexEntry = $definesEntryType && !$isSymfonyCoreFormType;
$field->setCustomOption(CollectionField::OPTION_ENTRY_IS_COMPLEX, $isComplexEntry);
}
$field->setFormattedValue($this->formatCollection($field, $context));
$this->configureEntryType($field, $entityDto, $context);
}
private function formatCollection(FieldDto $field, AdminContext $context): int|string
{
// when the field defines its own formatValue() callable, that callable runs later
// in CommonPostConfigurator and overwrites whatever we return here, so skip the
// text-joining work and avoid (string)-casting items that may not be valid UTF-8
if (null !== $field->getFormatValueCallable()) {
return $this->countNumElements($field->getValue());
}
$doctrineMetadata = $field->getDoctrineMetadata();
if ('array' !== $doctrineMetadata->get('type') && !$field->getValue() instanceof PersistentCollection) {
return $this->countNumElements($field->getValue());
}
$collectionItemsAsText = [];
foreach ($field->getValue() ?? [] as $item) {
if (!\is_string($item) && !$item instanceof \Stringable) {
return $this->countNumElements($field->getValue());
}
$collectionItemsAsText[] = (string) $item;
}
$isDetailAction = Action::DETAIL === $context->getCrud()->getCurrentAction();
$maxLength = $field->getCustomOption(CollectionField::OPTION_MAX_LENGTH) ?? ($isDetailAction ? 512 : 32);
return u(', ')->join($collectionItemsAsText)->truncate($maxLength, '…')->toString();
}
private function countNumElements(mixed $collection): int
{
if (null === $collection) {
return 0;
}
if (is_countable($collection)) {
return \count($collection);
}
if ($collection instanceof \Traversable) {
return iterator_count($collection);
}
return 0;
}
private function configureEntryType(FieldDto $fieldDto, EntityDto $entityDto, AdminContext $context): void
{
// entry_type and prototype options are only consumed when the field is
// rendered as a form (NEW/EDIT). On INDEX/DETAIL the field is rendered
// through formatCollection(), so the entry-type setup is wasted work
// and, more importantly, calling configureFields(PAGE_EDIT) on the
// target CRUD controller can run user code that expects a real entity
// instance (it has none here): see #7460.
if (!\in_array($context->getCrud()->getCurrentPage(), [Crud::PAGE_EDIT, Crud::PAGE_NEW], true)) {
return;
}
if (true === $fieldDto->getCustomOption(CollectionField::OPTION_ENTRY_USES_CRUD_FORM)) {
if (!$entityDto->getClassMetadata()->hasAssociation($fieldDto->getProperty())) {
throw new \RuntimeException(sprintf('The "%s" collection field of "%s" cannot use the "useEntryCrudForm()" method because it is not a Doctrine association.', $fieldDto->getProperty(), $context->getCrud()?->getControllerFqcn()));
}
if (null !== $fieldDto->getCustomOptions()->get(CollectionField::OPTION_ENTRY_TYPE)) {
throw new \RuntimeException(sprintf('The "%s" collection field of "%s" can render its entries using a Symfony Form (via the "setEntryType()" method) or using an EasyAdmin CRUD Form (via the "useEntryCrudForm()" method) but you cannot use both methods at the same time. Remove one of those two methods.', $fieldDto->getProperty(), $context->getCrud()?->getControllerFqcn()));
}
$targetCrudControllerFqcn = $fieldDto->getCustomOption(CollectionField::OPTION_ENTRY_CRUD_CONTROLLER_FQCN)
?? $context->getAdminControllers()->findCrudControllerByEntity($entityDto->getClassMetadata()->getAssociationTargetClass($fieldDto->getProperty()));
if (null === $targetCrudControllerFqcn) {
throw new \RuntimeException(sprintf('The "%s" collection field of "%s" wants to render its entries using an EasyAdmin CRUD form. However, no CRUD form was found related to this field. You can either create a CRUD controller for the entity "%s" or pass the CRUD controller to use as the first argument of the "useEntryCrudForm()" method.', $fieldDto->getProperty(), $context->getCrud()?->getControllerFqcn(), $entityDto->getClassMetadata()->getAssociationTargetClass($fieldDto->getProperty())));
}
} elseif (null === $fieldDto->getFormTypeOption('entry_type')
&& $entityDto->getClassMetadata()->hasAssociation($fieldDto->getProperty())) {
$targetCrudControllerFqcn = $context->getAdminControllers()->findCrudControllerByEntity($entityDto->getClassMetadata()->getAssociationTargetClass($fieldDto->getProperty()));
if (null === $targetCrudControllerFqcn) {
return;
}
} else {
return;
}
$targetEntityFqcn = $entityDto->getClassMetadata()->getAssociationTargetClass($fieldDto->getProperty());
$editEntityDto = $this->createEntityDto(
$targetEntityFqcn,
$targetCrudControllerFqcn,
Action::EDIT,
$fieldDto->getCustomOption(CollectionField::OPTION_ENTRY_CRUD_EDIT_PAGE_NAME) ?? Crud::PAGE_EDIT,
Crud::PAGE_EDIT,
);
$newEntityDto = $this->createEntityDto(
$targetEntityFqcn,
$targetCrudControllerFqcn,
Action::NEW,
$fieldDto->getCustomOption(CollectionField::OPTION_ENTRY_CRUD_NEW_PAGE_NAME) ?? Crud::PAGE_NEW,
Crud::PAGE_NEW,
);
// Build new collection entries through the embedded controller's createEntity()
// so its overrides (default values, factory pattern, etc.) are honored, instead of
// falling back to instantiating `$targetEntityFqcn` directly via Symfony Form.
// - `prototype_data` shapes the rendered prototype HTML (read at build time).
// - `entry_options.empty_data` is called by Symfony when binding a new (empty)
// entry on form submit, once per added entry.
// The context is intentionally NOT swapped to the embedded entity around the
// createEntity() call: callers commonly read `$this->getContext()->getEntity()`
// to populate the parent foreign key on the new entry, which only works when the
// parent context is left in place.
// See #6991.
$controllerFactory = $this->controllerFactory;
$requestStack = $this->requestStack;
$createEntryEntity = static function () use ($controllerFactory, $requestStack, $targetCrudControllerFqcn, $targetEntityFqcn): object {
$request = $requestStack->getMainRequest();
$controller = null !== $request
? $controllerFactory->getCrudControllerInstance($targetCrudControllerFqcn, Action::NEW, $request)
: null;
return null !== $controller
? $controller->createEntity($targetEntityFqcn)
: new $targetEntityFqcn();
};
$fieldDto->setFormTypeOption('entry_type', CrudFormType::class);
$fieldDto->setFormTypeOption('entry_options.entityDto', $editEntityDto);
$fieldDto->setFormTypeOption('prototype_options.entityDto', $newEntityDto);
$fieldDto->setFormTypeOptionIfNotSet('prototype_data', $createEntryEntity());
$fieldDto->setFormTypeOptionIfNotSet('entry_options.empty_data', $createEntryEntity);
// The assets declared by entry fields (e.g. TextEditorField, FileField, a nested
// CollectionField...) live on the entry EntityDto, not on the parent CollectionField.
// Propagate them up so that AbstractCrudController::getFieldAssets(), which only
// walks top-level fields, picks them up and outputs the required CSS/JS on the
// form page that hosts the embedded CRUD form. See #6127.
$assets = $fieldDto->getAssets();
foreach ([$editEntityDto, $newEntityDto] as $entryEntityDto) {
foreach ($entryEntityDto->getFields() ?? [] as $entryField) {
$assets = $assets->mergeWith($entryField->getAssets());
}
}
$fieldDto->setAssets($assets);
}
/**
* @param class-string $targetEntityFqcn
* @param class-string $targetCrudControllerFqcn
*/
private function createEntityDto(string $targetEntityFqcn, string $targetCrudControllerFqcn, string $crudAction, string $crudControllerPageName, string $crudPageName): EntityDto
{
$entityDto = $this->entityFactory->create($targetEntityFqcn);
$request = $this->requestStack->getMainRequest();
$crudController = $this->controllerFactory->getCrudControllerInstance(
$targetCrudControllerFqcn,
$crudAction,
$request
);
$originalContext = $this->adminContextProvider->getContext();
// temporarily swap AdminContext with the collection's EntityDto
// (this allows e.g. the CRUD controller of the collection entry to get the correct entity instance)
if ($originalContext instanceof AdminContext && null !== $request) {
$collectionContext = $originalContext->withEntity($entityDto);
$request->attributes->set(EA::CONTEXT_REQUEST_ATTRIBUTE, $collectionContext);
}
try {
$fields = $crudController->configureFields($crudControllerPageName);
$this->fieldFactory->processFields($entityDto, new FieldCollection($fields), $crudPageName);
} finally {
// restore the original context
if ($originalContext instanceof AdminContext && null !== $request) {
$request->attributes->set(EA::CONTEXT_REQUEST_ATTRIBUTE, $originalContext);
}
}
return $entityDto;
}
}