forked from EasyCorp/EasyAdminBundle
/
EasyAdminExtension.php
443 lines (378 loc) · 18.4 KB
/
EasyAdminExtension.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
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
<?php
/*
* This file is part of the EasyAdminBundle.
*
* (c) Javier Eguiluz <javier.eguiluz@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace JavierEguiluz\Bundle\EasyAdminBundle\DependencyInjection;
use Symfony\Component\HttpKernel\DependencyInjection\Extension;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Loader\XmlFileLoader;
use Symfony\Component\Config\FileLocator;
class EasyAdminExtension extends Extension
{
private $defaultActionConfiguration = array(
'name' => null, // either the name of a controller method or an application route (it depends on the 'type' option)
'type' => 'method', // 'method' if the action is a controller method; 'route' if it's an application route
'label' => null, // action label (displayed as link or button) (if 'null', autogenerate it)
'class' => '', // the CSS class applied to the button/link displayed by the action
'icon' => null, // the name of the FontAwesome icon to display next to the 'label' (doesn't include the 'fa-' prefix)
);
public function load(array $configs, ContainerBuilder $container)
{
// process bundle's configuration parameters
$backendConfiguration = $this->processConfiguration(new Configuration(), $configs);
$backendConfiguration['entities'] = $this->getEntitiesConfiguration($backendConfiguration['entities']);
$backendConfiguration = $this->processEntityActions($backendConfiguration);
$container->setParameter('easyadmin.config', $backendConfiguration);
// load bundle's services
$loader = new XmlFileLoader($container, new FileLocator(__DIR__.'/../Resources/config'));
$loader->load('services.xml');
}
/**
* Processes, normalizes and initializes the configuration of the entities
* that are managed by the backend. Several configuration formats are allowed,
* so this method normalizes them all.
*
* @param array $entitiesConfiguration
*
* @return array The full entity configuration
*/
public function getEntitiesConfiguration(array $entitiesConfiguration)
{
if (0 === count($entitiesConfiguration)) {
return $entitiesConfiguration;
}
$configuration = $this->normalizeEntitiesConfiguration($entitiesConfiguration);
$configuration = $this->processEntitiesConfiguration($configuration);
return $configuration;
}
/**
* Transforms the two simple configuration formats into the full expanded
* configuration. This allows to reuse the same method to process any of the
* different configuration formats.
*
* These are the two simple formats allowed:
*
* # Config format #1: no custom entity label
* easy_admin:
* entities:
* - AppBundle\Entity\User
*
* # Config format #2: simple config with custom entity label
* easy_admin:
* entities:
* User: AppBundle\Entity\User
*
* And this is the full expanded configuration syntax generated by this method:
*
* # Config format #3: expanded entity configuration with 'class' parameter
* easy_admin:
* entities:
* User:
* class: AppBundle\Entity\User
*
* # Config format #3 can optionally define a custom entity label
* easy_admin:
* entities:
* User:
* class: AppBundle\Entity\User
* label: 'Clients'
*
* @param array $entitiesConfiguration The entity configuration in one of the simplified formats
*
* @return array The normalized configuration
*/
private function normalizeEntitiesConfiguration(array $entitiesConfiguration)
{
$normalizedConfiguration = array();
foreach ($entitiesConfiguration as $entityLabel => $entityConfiguration) {
// config formats #1 and #2
if (!is_array($entityConfiguration)) {
$entityConfiguration = array('class' => $entityConfiguration);
}
// if config format #3 is used, ensure that it defines the 'class' option
if (!isset($entityConfiguration['class'])) {
throw new \RuntimeException(sprintf('The "%s" entity must define its associated Doctrine entity class using the "class" option.', $entityLabel));
}
$entityClassParts = explode('\\', $entityConfiguration['class']);
$entityClassName = end($entityClassParts);
# if config format #3 defines the 'label' option, use its value.
# otherwise, infer the entity label from its configuration.
if (!isset($entityConfiguration['label'])) {
// config format #1 doesn't define any entity label because configuration is
// just a plain numeric array (the label is the integer key of that array).
// In that case, use the entity class name as its label
$entityConfiguration['label'] = is_integer($entityLabel) ? $entityClassName : $entityLabel;
}
$entityName = $this->getUniqueEntityName($entityClassName, array_keys($normalizedConfiguration));
$entityConfiguration['name'] = $entityName;
$normalizedConfiguration[$entityName] = $entityConfiguration;
}
return $normalizedConfiguration;
}
/**
* Merges all the actions that can be configured in the backend and normalizes
* them to get the final action configuration for each entity view.
*
* @param array $backendConfiguration
*
* @return array
*/
public function processEntityActions(array $backendConfiguration)
{
$entitiesConfiguration = array();
foreach ($backendConfiguration['entities'] as $entityName => $entityConfiguration) {
foreach (array('edit', 'list', 'new', 'show') as $view) {
$defaultActions = $this->getDefaultActions($view);
$backendActions = isset($backendConfiguration[$view]['actions']) ? $backendConfiguration[$view]['actions'] : array();
$backendActions = $this->normalizeActionsConfiguration($backendActions);
$defaultViewActions = array_replace($defaultActions, $backendActions);
$defaultViewActions = $this->filterRemovedActions($defaultViewActions);
$entityActions = isset($entityConfiguration[$view]['actions']) ? $entityConfiguration[$view]['actions'] : array();
$entityActions = $this->normalizeActionsConfiguration($entityActions);
$viewActions = array_replace($defaultViewActions, $entityActions);
$viewActions = $this->filterRemovedActions($viewActions);
// 'list' action is mandatory for all views
if (!array_key_exists('list', $viewActions)) {
$viewActions = array_merge($viewActions, $this->normalizeActionsConfiguration(array('list')));
}
$entityConfiguration[$view]['actions'] = $viewActions;
}
$entitiesConfiguration[$entityName] = $entityConfiguration;
}
$backendConfiguration['entities'] = $entitiesConfiguration;
return $backendConfiguration;
}
/**
* Returns the default actions defined by EasyAdmin for the given view.
* This allows to provide some nice defaults for backends that don't
* define their own actions.
*
* @param string $view
*
* @return array
*/
private function getDefaultActions($view)
{
// basic configuration for default actions
$actions = $this->normalizeActionsConfiguration(array(
array('name' => 'delete', 'label' => 'action.delete', 'type' => 'method', 'icon' => 'trash'),
array('name' => 'edit', 'label' => 'action.edit', 'type' => 'method', 'icon' => 'edit'),
array('name' => 'new', 'label' => 'action.new', 'type' => 'method'),
array('name' => 'search', 'label' => 'action.search', 'type' => 'method'),
array('name' => 'show', 'label' => 'action.show', 'type' => 'method'),
array('name' => 'list', 'label' => 'action.list', 'type' => 'method'),
));
// configure which actions are enabled for each view
$actionsPerView = array(
'edit' => array('delete' => $actions['delete'], 'list' => $actions['list']),
'list' => array('show' => $actions['show'], 'edit' => $actions['edit'], 'search' => $actions['search'], 'new' => $actions['new']),
'new' => array('list' => $actions['list']),
'show' => array('delete' => $actions['delete'], 'list' => $actions['list'], 'edit' => $actions['edit']),
);
// minor tweaks for some action + view combinations
$actionsPerView['list']['edit']['icon'] = null;
return $actionsPerView[$view];
}
/**
* Transforms the different action configuration formats into a normalized
* and expanded format. These are the two simple formats allowed:
*
* # Config format #1: no custom option
* easy_admin:
* entities:
* User:
* list:
* actions: ['search', 'show', 'grantAccess']
*
* # Config format #2: one or more actions define any of their options
* easy_admin:
* entities:
* User:
* list:
* actions: ['search', { name: 'show', label: 'Show', 'icon': 'user' }, 'grantAccess']
*
* @param array $actionConfiguration
*
* @return array
*/
private function normalizeActionsConfiguration(array $actionConfiguration)
{
$configuration = array();
foreach ($actionConfiguration as $action) {
if (!is_string($action) && !is_array($action)) {
throw new \RuntimeException('The values of the "actions" option can only be strings or arrays.');
}
// config format #1
if (is_string($action)) {
$action = array('name' => $action);
}
$normalizedConfiguration = array_replace($this->defaultActionConfiguration, $action);
// 'name' is the only mandatory option for actions
if (!isset($action['name'])) {
throw new \RuntimeException('When using the expanded configuration format for actions, you must define their "name" option.');
}
// 'name' value is used as the class method name or the Symfony route name
// check that its value complies with the PHP method name regexp (the leading dash
// is exceptionally allowed to support the configuration format of removed actions)
if (!preg_match('/^-?[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*$/', $action['name'], $matchActionName)) {
throw new \InvalidArgumentException(sprintf('The name of the "%s" action contains invalid characters (allowed: letters, numbers, underscores).', $action['name']));
}
if (!isset($action['type'])) {
$action['type'] = 'method';
}
$actionName = $normalizedConfiguration['name'];
// use the special 'action.<action name>' label for the default actions
if (null === $normalizedConfiguration['label'] && in_array($actionName, array('delete', 'edit', 'new', 'search', 'show', 'list'))) {
$normalizedConfiguration['label'] = 'action.'.$actionName;
}
// the rest of actions without a custom label use their name as label
if (null === $normalizedConfiguration['label']) {
// copied from Symfony\Component\Form\FormRenderer::humanize() (author: Bernhard Schussek <bschussek@gmail.com>)
$label = ucfirst(trim(strtolower(preg_replace(array('/([A-Z])/', '/[_\s]+/'), array('_$1', ' '), $actionName))));
$normalizedConfiguration['label'] = $label;
}
$configuration[$actionName] = $normalizedConfiguration;
}
return $configuration;
}
/**
* Removes the actions marked as deleted from the given actions configuration.
*
* @param array $actionsConfiguration
*
* @return array
*/
private function filterRemovedActions(array $actionsConfiguration)
{
// if the name of the action starts with a '-' dash, remove it
$removedActions = array_filter($actionsConfiguration, function ($action) {
return '-' === $action['name']{0};
});
if (empty($removedActions)) {
return $actionsConfiguration;
}
return array_filter($actionsConfiguration, function ($action) use ($removedActions) {
// e.g. '-search' action name removes both '-search' and 'search' (if exists)
return !array_key_exists($action['name'], $removedActions)
&& !array_key_exists('-'.$action['name'], $removedActions);
});
}
/**
* Normalizes and initializes the configuration of the given entities to
* simplify the option processing of the other methods and functions.
*
* @param array $entitiesConfiguration
*
* @return array The configured entities
*/
private function processEntitiesConfiguration(array $entitiesConfiguration)
{
$entities = array();
foreach ($entitiesConfiguration as $entityName => $entityConfiguration) {
// copy the original entity configuration to not lose any of its options
$config = $entityConfiguration;
// if the special 'form' view is defined, use its options to complete
// the configuration for the 'new' and 'edit' views
if (isset($config['form'])) {
$config['new'] = isset($config['new']) ? array_replace($config['form'], $config['new']) : $config['form'];
$config['edit'] = isset($config['edit']) ? array_replace($config['form'], $config['edit']) : $config['form'];
}
// configuration for the views related to the entity ('list', 'edit', etc.)
foreach (array('edit', 'list', 'new', 'show') as $view) {
// if needed, initialize options to simplify further configuration processing
if (!isset($config[$view])) {
$config[$view] = array('fields' => array());
}
if (!isset($config[$view]['fields'])) {
$config[$view]['fields'] = array();
}
if (count($config[$view]['fields']) > 0) {
$config[$view]['fields'] = $this->normalizeFieldsConfiguration($config[$view]['fields'], $view, $entityConfiguration);
}
}
$entities[$entityName] = $config;
}
return $entities;
}
/**
* The name of the entity is used in the URLs of the application to define the
* entity which should be used for each view. Obviously, the entity name
* must be unique in the application to identify entities unequivocally.
*
* This method ensures that all entity names are unique by appending some suffix
* to repeated names until they are unique.
*
* @param array $entitiesConfiguration
*
* @return array The entities configuration with unique entity names
*/
private function getUniqueEntityName($entityName, $existingEntityNames)
{
$uniqueName = $entityName;
while (in_array($uniqueName, $existingEntityNames)) {
$uniqueName .= '_';
}
return $uniqueName;
}
/**
* Views can define their fields using two different formats:
*
* # Config format #1: simple configuration
* easy_admin:
* Client:
* # ...
* list:
* fields: ['id', 'name', 'email']
*
* # Config format #2: extended configuration
* easy_admin:
* Client:
* # ...
* list:
* fields: ['id', 'name', { property: 'email', label: 'Contact' }]
*
* This method processes both formats to produce a common form field configuration
* format used in the rest of the application.
*
* @param array $fieldsConfiguration
* @param string $view The current view (this argument is needed to create good error messages)
* @param array $entityConfiguration The full configuration of the entity this field belongs to
*
* @return array The configured entity fields
*/
private function normalizeFieldsConfiguration(array $fieldsConfiguration, $view, array $entityConfiguration)
{
$fields = array();
foreach ($fieldsConfiguration as $field) {
if (!is_string($field) && !is_array($field)) {
throw new \RuntimeException(sprintf('The values of the "fields" option for the "%s" view of the "%s" entity can only be strings or arrays.', $view, $entityConfiguration['class']));
}
if (is_string($field)) {
// Config format #1: field is just a string representing the entity property
$fieldConfiguration = array('property' => $field);
} else {
// Config format #1: field is an array that defines one or more
// options. check that the mandatory 'property' option is set
if (!array_key_exists('property', $field)) {
throw new \RuntimeException(sprintf('One of the values of the "fields" option for the "%s" view of the "%s" entity does not define the "property" option.', $view, $entityConfiguration['class']));
}
$fieldConfiguration = $field;
}
// for 'image' type fields, if the entity defines an 'image_base_path'
// option, but the field does not, use the value defined by the entity
if (isset($fieldConfiguration['type']) && 'image' === $fieldConfiguration['type']) {
if (!isset($fieldConfiguration['base_path']) && isset($entityConfiguration['image_base_path'])) {
$fieldConfiguration['base_path'] = $entityConfiguration['image_base_path'];
}
}
$fieldName = $fieldConfiguration['property'];
$fields[$fieldName] = $fieldConfiguration;
}
return $fields;
}
}