-
-
Notifications
You must be signed in to change notification settings - Fork 1k
/
AdminController.php
721 lines (599 loc) · 24.4 KB
/
AdminController.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
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
<?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.
*
* Some parts of this file are copied and/or inspired by the
* DoctrineCRUDGenerator included in the SensioGeneratorBundle.
* License: MIT License
* Copyright: (c) Fabien Potencier <fabien@symfony.com>
* Source: https://github.com/sensiolabs/SensioGeneratorBundle
*/
namespace JavierEguiluz\Bundle\EasyAdminBundle\Controller;
use Doctrine\DBAL\Platforms\PostgreSqlPlatform;
use Doctrine\ORM\EntityManager;
use Doctrine\ORM\Mapping\ClassMetadataInfo;
use Symfony\Component\EventDispatcher\GenericEvent;
use Symfony\Component\Form\Form;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Pagerfanta\Pagerfanta;
use Pagerfanta\Adapter\DoctrineORMAdapter;
use JavierEguiluz\Bundle\EasyAdminBundle\Event\EasyAdminEvents;
use JavierEguiluz\Bundle\EasyAdminBundle\Exception\NoEntitiesConfiguredException;
use JavierEguiluz\Bundle\EasyAdminBundle\Exception\UndefinedEntityException;
use JavierEguiluz\Bundle\EasyAdminBundle\Exception\EntityNotFoundException;
use JavierEguiluz\Bundle\EasyAdminBundle\Exception\ForbiddenActionException;
/**
* Class AdminController.
*/
class AdminController extends Controller
{
protected $config;
protected $entity = array();
/** @var Request */
protected $request;
/** @var EntityManager */
protected $em;
/**
* @Route("/", name="admin")
*
* @param Request $request
*
* @return RedirectResponse|Response
*/
public function indexAction(Request $request)
{
$this->initialize($request);
$action = $request->query->get('action', 'list');
// for now, the homepage redirects to the 'list' action of the first entity
if (null === $request->query->get('entity')) {
return $this->redirect($this->generateUrl('admin', array(
'action' => $action,
'entity' => $this->getNameOfTheFirstConfiguredEntity(),
)));
}
if (!$this->isActionAllowed($action)) {
throw new ForbiddenActionException(array('action' => $action));
}
$customMethodName = $action.$this->entity['name'].'Action';
$defaultMethodName = $action.'Action';
return method_exists($this, $customMethodName) ? $this->{$customMethodName}() : $this->{$defaultMethodName}();
}
/**
* Utility method which initializes the configuration of the entity on which
* the user is performing the action.
*
* @param Request $request
*
* @return null
*/
protected function initialize(Request $request)
{
$this->dispatch(EasyAdminEvents::PRE_INITIALIZE);
$this->config = $this->container->getParameter('easyadmin.config');
if (0 === count($this->config['entities'])) {
throw new NoEntitiesConfiguredException();
}
// this condition happens when accessing the backend homepage, which
// then redirects to the 'list' action of the first configured entity
if (null === $entityName = $request->query->get('entity')) {
return;
}
if (!array_key_exists($entityName, $this->config['entities'])) {
throw new UndefinedEntityException(array('entity_name' => $entityName));
}
$this->entity = $this->get('easyadmin.configurator')->getEntityConfiguration($entityName);
if (!$request->query->has('sortField')) {
$request->query->set('sortField', $this->entity['primary_key_field_name']);
}
if (!$request->query->has('sortDirection') || !in_array(strtoupper($request->query->get('sortDirection')), array('ASC', 'DESC'))) {
$request->query->set('sortDirection', 'DESC');
}
$this->em = $this->getDoctrine()->getManagerForClass($this->entity['class']);
$this->request = $request;
$this->dispatch(EasyAdminEvents::POST_INITIALIZE);
}
private function dispatch($eventName, array $arguments = array())
{
$arguments = array_replace(array(
'config' => $this->config,
'em' => $this->em,
'entity' => $this->entity,
'request' => $this->request,
), $arguments);
$subject = isset($arguments['paginator']) ? $arguments['paginator'] : $arguments['entity'];
$event = new GenericEvent($subject, $arguments);
$this->get('event_dispatcher')->dispatch($eventName, $event);
}
/**
* The method that is executed when the user performs a 'list' action on an entity.
*
* @return Response
*/
protected function listAction()
{
$this->dispatch(EasyAdminEvents::PRE_LIST);
$fields = $this->entity['list']['fields'];
$paginator = $this->findAll($this->entity['class'], $this->request->query->get('page', 1), $this->config['list']['max_results'], $this->request->query->get('sortField'), $this->request->query->get('sortDirection'));
$this->dispatch(EasyAdminEvents::POST_LIST, array('paginator' => $paginator));
return $this->render($this->entity['templates']['list'], array(
'paginator' => $paginator,
'fields' => $fields,
));
}
/**
* The method that is executed when the user performs a 'edit' action on an entity.
*
* @return RedirectResponse|Response
*/
protected function editAction()
{
$this->dispatch(EasyAdminEvents::PRE_EDIT);
if ($this->request->isXmlHttpRequest()) {
return $this->ajaxEdit();
}
$id = $this->request->query->get('id');
if (!$entity = $this->em->getRepository($this->entity['class'])->find($id)) {
throw new EntityNotFoundException(array('action' => 'edit', 'entity' => $this->entity, 'entity_id' => $id));
}
$fields = $this->entity['edit']['fields'];
if (method_exists($this, $customMethodName = 'create'.$this->entity['name'].'EditForm')) {
$editForm = $this->{$customMethodName}($entity, $fields);
} else {
$editForm = $this->createEditForm($entity, $fields);
}
$deleteForm = $this->createDeleteForm($this->entity['name'], $id);
$editForm->handleRequest($this->request);
if ($editForm->isValid()) {
$this->dispatch(EasyAdminEvents::PRE_UPDATE, array('entity' => $entity));
if (method_exists($this, $customMethodName = 'preUpdate'.$this->entity['name'].'Entity')) {
$this->{$customMethodName}($entity);
} else {
$this->preUpdateEntity($entity);
}
$this->em->flush();
$this->dispatch(EasyAdminEvents::POST_UPDATE, array('entity' => $entity));
$refererUrl = $this->request->query->get('referer', '');
return !empty($refererUrl)
? $this->redirect(urldecode($refererUrl))
: $this->redirect($this->generateUrl('admin', array('action' => 'list', 'entity' => $this->entity['name'])));
}
$this->dispatch(EasyAdminEvents::POST_EDIT);
return $this->render($this->entity['templates']['edit'], array(
'form' => $editForm->createView(),
'entity_fields' => $fields,
'entity' => $entity,
'delete_form' => $deleteForm->createView(),
));
}
/**
* The method that is executed when the user performs a 'show' action on an entity.
*
* @return Response
*/
protected function showAction()
{
$this->dispatch(EasyAdminEvents::PRE_SHOW);
$id = $this->request->query->get('id');
if (!$entity = $this->em->getRepository($this->entity['class'])->find($id)) {
throw new EntityNotFoundException(array('action' => 'show', 'entity' => $this->entity, 'entity_id' => $id));
}
$fields = $this->entity['show']['fields'];
$deleteForm = $this->createDeleteForm($this->entity['name'], $id);
$this->dispatch(EasyAdminEvents::POST_SHOW, array(
'deleteForm' => $deleteForm,
'fields' => $fields,
'entity' => $entity,
));
return $this->render($this->entity['templates']['show'], array(
'entity' => $entity,
'fields' => $fields,
'delete_form' => $deleteForm->createView(),
));
}
/**
* The method that is executed when the user performs a 'new' action on an entity.
*
* @return RedirectResponse|Response
*/
protected function newAction()
{
$this->dispatch(EasyAdminEvents::PRE_NEW);
if (method_exists($this, $customMethodName = 'createNew'.$this->entity['name'].'Entity')) {
$entity = $this->{$customMethodName}();
} else {
$entity = $this->createNewEntity();
}
$fields = $this->entity['new']['fields'];
if (method_exists($this, $customMethodName = 'create'.$this->entity['name'].'NewForm')) {
$newForm = $this->{$customMethodName}($entity, $fields);
} else {
$newForm = $this->createNewForm($entity, $fields);
}
$newForm->handleRequest($this->request);
if ($newForm->isValid()) {
$this->dispatch(EasyAdminEvents::PRE_PERSIST, array('entity' => $entity));
if (method_exists($this, $customMethodName = 'prePersist'.$this->entity['name'].'Entity')) {
$this->{$customMethodName}($entity);
} else {
$this->prePersistEntity($entity);
}
$this->em->persist($entity);
$this->em->flush();
$this->dispatch(EasyAdminEvents::POST_PERSIST, array('entity' => $entity));
$refererUrl = $this->request->query->get('referer', '');
return $this->redirect($this->generateUrl('admin', array('action' => 'list', 'entity' => $this->entity['name'])));
}
$this->dispatch(EasyAdminEvents::POST_NEW, array(
'entity_fields' => $fields,
'form' => $newForm,
'entity' => $entity,
));
return $this->render($this->entity['templates']['new'], array(
'form' => $newForm->createView(),
'entity_fields' => $fields,
'entity' => $entity,
));
}
/**
* The method that is executed when the user performs a 'delete' action to
* remove any entity.
*
* @return RedirectResponse
*/
protected function deleteAction()
{
$this->dispatch(EasyAdminEvents::PRE_DELETE);
if ('DELETE' !== $this->request->getMethod()) {
return $this->redirect($this->generateUrl('admin', array('action' => 'list', 'entity' => $this->entity['name'])));
}
$id = $this->request->query->get('id');
$form = $this->createDeleteForm($this->entity['name'], $id);
$form->handleRequest($this->request);
if ($form->isValid()) {
if (!$entity = $this->em->getRepository($this->entity['class'])->find($id)) {
throw new EntityNotFoundException(array('action' => 'delete', 'entity' => $this->entity, 'entity_id' => $id));
}
$this->dispatch(EasyAdminEvents::PRE_REMOVE, array('entity' => $entity));
if (method_exists($this, $customMethodName = 'preRemove'.$this->entity['name'].'Entity')) {
$this->{$customMethodName}($entity);
} else {
$this->preRemoveEntity($entity);
}
$this->em->remove($entity);
$this->em->flush();
$this->dispatch(EasyAdminEvents::POST_REMOVE, array('entity' => $entity));
}
$refererUrl = $this->request->query->get('referer', '');
$this->dispatch(EasyAdminEvents::POST_DELETE);
return !empty($refererUrl)
? $this->redirect(urldecode($refererUrl))
: $this->redirect($this->generateUrl('admin', array('action' => 'list', 'entity' => $this->entity['name'])));
}
/**
* The method that is executed when the user performs a query on an entity.
*
* @return Response
*/
protected function searchAction()
{
$this->dispatch(EasyAdminEvents::PRE_SEARCH);
$searchableFields = $this->entity['search']['fields'];
$paginator = $this->findBy($this->entity['class'], $this->request->query->get('query'), $searchableFields, $this->request->query->get('page', 1), $this->config['list']['max_results']);
$fields = $this->entity['list']['fields'];
$this->dispatch(EasyAdminEvents::POST_SEARCH, array(
'fields' => $fields,
'paginator' => $paginator,
));
return $this->render($this->entity['templates']['list'], array(
'paginator' => $paginator,
'fields' => $fields,
));
}
/**
* Modifies the entity properties via an Ajax call. Currently it's used for
* changing the value of boolean properties when the user clicks on the
* flip switched displayed for boolean values in the 'list' action.
*/
protected function ajaxEdit()
{
if (!$entity = $this->em->getRepository($this->entity['class'])->find($this->request->query->get('id'))) {
throw new \Exception('The entity does not exist.');
}
$propertyName = $this->request->query->get('property');
$propertyMetadata = $this->entity['list']['fields'][$propertyName];
if (!isset($this->entity['list']['fields'][$propertyName]) || 'toggle' != $propertyMetadata['dataType']) {
throw new \Exception(sprintf('The "%s" property is not a switchable toggle.', $propertyName));
}
if (!$propertyMetadata['canBeSet']) {
throw new \Exception(sprintf('It\'s not possible to toggle the value of the "%s" boolean property of the "%s" entity.', $propertyName, $this->entity['name']));
}
$newValue = ('true' === strtolower($this->request->query->get('newValue'))) ? true : false;
if (null !== $setter = $propertyMetadata['setter']) {
$entity->{$setter}($newValue);
} else {
$entity->{$propertyName} = $newValue;
}
$this->em->flush();
return new Response((string) $newValue);
}
/**
* Creates a new object of the current managed entity.
* This method is mostly here for override convenience, because it allows
* the user to use his own method to customize the entity instantiation.
*
* @return object
*/
protected function createNewEntity()
{
$entityFullyQualifiedClassName = $this->entity['class'];
return new $entityFullyQualifiedClassName();
}
/**
* Allows applications to modify the entity associated with the item being
* created before persisting it.
*
* @param object $entity
*
* @return null
*/
protected function prePersistEntity($entity)
{
}
/**
* Allows applications to modify the entity associated with the item being
* edited before persisting it.
*
* @param object $entity
*
* @return null
*/
protected function preUpdateEntity($entity)
{
}
/**
* Allows applications to modify the entity associated with the item being
* deleted before removing it.
*
* @param object $entity
*
* @return null
*/
protected function preRemoveEntity($entity)
{
}
/**
* Performs a database query to get all the records related to the given
* entity. It supports pagination and field sorting.
*
* @param string $entityClass
* @param int $page
* @param int $maxPerPage
* @param string|null $sortField
* @param string|null $sortDirection
*
* @return Pagerfanta The paginated query results
*/
protected function findAll($entityClass, $page = 1, $maxPerPage = 15, $sortField = null, $sortDirection = null)
{
$query = $this->em->createQueryBuilder()
->select('entity')
->from($entityClass, 'entity')
;
if (null !== $sortField) {
if (empty($sortDirection) || !in_array(strtoupper($sortDirection), array('ASC', 'DESC'))) {
$sortDirection = 'DESC';
}
$query->orderBy('entity.'.$sortField, $sortDirection);
}
$paginator = new Pagerfanta(new DoctrineORMAdapter($query, false));
$paginator->setMaxPerPage($maxPerPage);
$paginator->setCurrentPage($page);
return $paginator;
}
/**
* Performs a database query based on the search query provided by the user.
* It supports pagination and field sorting.
*
* @param string $entityClass
* @param string $searchQuery
* @param array $searchableFields
* @param int $page
* @param int $maxPerPage
*
* @return Pagerfanta The paginated query results
*/
protected function findBy($entityClass, $searchQuery, array $searchableFields, $page = 1, $maxPerPage = 15)
{
$dbIsPostgreSql = $this->isPostgreSqlUsedByEntity($entityClass);
$queryBuilder = $this->em->createQueryBuilder()->select('entity')->from($entityClass, 'entity');
$queryConditions = $queryBuilder->expr()->orX();
$queryParameters = array();
foreach ($searchableFields as $name => $metadata) {
// PostgreSQL doesn't allow to compare strings values with non-string columns (e.g. 'id')
if ($dbIsPostgreSql && !in_array($metadata['type'], array('text', 'string'))) {
continue;
}
if (in_array($metadata['dataType'], array('text', 'string'))) {
$queryConditions->add(sprintf('entity.%s LIKE :query', $name));
$queryParameters['query'] = '%'.$searchQuery.'%';
} else {
$queryConditions->add(sprintf('entity.%s IN (:words)', $name));
$queryParameters['words'] = explode(' ', $searchQuery);
}
}
$queryBuilder->add('where', $queryConditions)->setParameters($queryParameters);
$paginator = new Pagerfanta(new DoctrineORMAdapter($queryBuilder, false));
$paginator->setMaxPerPage($maxPerPage);
$paginator->setCurrentPage($page);
return $paginator;
}
/**
* Creates the form used to edit an entity.
*
* @param object $entity
* @param array $entityProperties
*
* @return Form
*/
protected function createEditForm($entity, array $entityProperties)
{
return $this->createEntityForm($entity, $entityProperties, 'edit');
}
/**
* Creates the form used to create an entity.
*
* @param object $entity
* @param array $entityProperties
*
* @return Form
*/
protected function createNewForm($entity, array $entityProperties)
{
return $this->createEntityForm($entity, $entityProperties, 'new');
}
/**
* Creates the form used to create or edit an entity.
*
* @param object $entity
* @param array $entityProperties
* @param string $view The name of the view where this form is used ('new' or 'edit')
*
* @return Form
*/
protected function createEntityForm($entity, array $entityProperties, $view)
{
$formCssClass = array_reduce($this->config['design']['form_theme'], function ($previousClass, $formTheme) {
return sprintf('theme-%s %s', strtolower(str_replace('.html.twig', '', basename($formTheme))), $previousClass);
});
$formBuilder = $this->createFormBuilder($entity, array(
'data_class' => $this->entity['class'],
'attr' => array('class' => $formCssClass, 'id' => $view.'-form'),
));
foreach ($entityProperties as $name => $metadata) {
$formFieldOptions = array();
if ('association' === $metadata['fieldType'] && in_array($metadata['associationType'], array(ClassMetadataInfo::ONE_TO_MANY, ClassMetadataInfo::MANY_TO_MANY))) {
continue;
}
if ('collection' === $metadata['fieldType']) {
$formFieldOptions = array('allow_add' => true, 'allow_delete' => true);
if (version_compare(\Symfony\Component\HttpKernel\Kernel::VERSION, '2.5.0', '>=')) {
$formFieldOptions['delete_empty'] = true;
}
}
$formFieldOptions['attr']['field_type'] = $metadata['fieldType'];
$formFieldOptions['attr']['field_css_class'] = $metadata['class'];
$formFieldOptions['attr']['field_help'] = $metadata['help'];
$formBuilder->add($name, $metadata['fieldType'], $formFieldOptions);
}
return $formBuilder->getForm();
}
/**
* It returns the name of the first entity configured in the backend. It's
* mainly used to redirect the homepage of the backend to the listing of the
* first configured entity.
*
* @return mixed
*/
protected function getNameOfTheFirstConfiguredEntity()
{
$entityNames = array_keys($this->config['entities']);
return $entityNames[0];
}
/**
* Creates the form used to delete an entity. It must be a form because
* the deletion of the entity are always performed with the 'DELETE' HTTP method,
* which requires a form to work in the current browsers.
*
* @param string $entityName
* @param int $entityId
*
* @return Form
*/
protected function createDeleteForm($entityName, $entityId)
{
return $this->createFormBuilder()
->setAction($this->generateUrl('admin', array('action' => 'delete', 'entity' => $entityName, 'id' => $entityId)))
->setMethod('DELETE')
->add('submit', 'submit', array('label' => 'Delete'))
->getForm()
;
}
/**
* Utility shortcut to render a template as a 404 error page.
*
* @param string $view
* @param array $parameters
*
* @deprecated Use an appropriate exception instead of this method.
* @return Response
*/
protected function render404error($view, array $parameters = array())
{
return $this->render($view, $parameters, new Response('', 404));
}
/**
* Utility method that checks if the given action is allowed for
* the current entity.
*
* @param string $actionName
*
* @return bool
*/
protected function isActionAllowed($actionName)
{
return false === in_array($actionName, $this->entity['disabled_actions'], true);
}
/**
* Utility shortcut to render an error when the requested action is not allowed
* for the given entity.
*
* @param string $action
*
* @deprecated Use the ForbiddenException instead of this method.
* @return Response
*/
protected function renderForbiddenActionError($action)
{
return $this->render('@EasyAdmin/error/forbidden_action.html.twig', array('action' => $action), new Response('', 403));
}
/**
* It renders the main CSS applied to the backend design. This controller
* allows to generate dynamic CSS files that use variables without the need
* to set up a CSS preprocessing toolchain.
*
* @Route("/_css/admin.css", name="_easyadmin_render_css")
*/
public function renderCssAction()
{
$config = $this->container->getParameter('easyadmin.config');
$cssContent = $this->renderView('@EasyAdmin/css/admin.css.twig', array(
'brand_color' => $config['design']['brand_color'],
'color_scheme' => $config['design']['color_scheme'],
));
$response = new Response($cssContent, 200, array('Content-Type' => 'text/css'));
$response->setPublic();
$response->setSharedMaxAge(600);
return $response;
}
/**
* Returns true if the data of the given entity are stored in a database
* of Type PostgreSQL.
*
* @param string $entityClass
* @return boolean
*/
private function isPostgreSqlUsedByEntity($entityClass)
{
$em = $this->get('doctrine')->getManagerForClass($entityClass);
return $em->getConnection()->getDatabasePlatform() instanceof PostgreSqlPlatform;
}
}