vendor/easycorp/easyadmin-bundle/src/EventListener/RequestPostInitializeListener.php line 33

Open in your IDE?
  1. <?php
  2. namespace EasyCorp\Bundle\EasyAdminBundle\EventListener;
  3. use Doctrine\Persistence\ManagerRegistry;
  4. use EasyCorp\Bundle\EasyAdminBundle\Exception\EntityNotFoundException;
  5. use Symfony\Component\EventDispatcher\GenericEvent;
  6. use Symfony\Component\HttpFoundation\RequestStack;
  7. /**
  8.  * Adds some custom attributes to the request object to store information
  9.  * related to EasyAdmin.
  10.  *
  11.  * @author Maxime Steinhausser <maxime.steinhausser@gmail.com>
  12.  */
  13. class RequestPostInitializeListener
  14. {
  15.     private $doctrine;
  16.     private $requestStack;
  17.     public function __construct(ManagerRegistry $doctrineRequestStack $requestStack null)
  18.     {
  19.         $this->doctrine $doctrine;
  20.         $this->requestStack $requestStack;
  21.     }
  22.     /**
  23.      * Adds to the request some attributes with useful information, such as the
  24.      * current entity and the selected item, if any.
  25.      *
  26.      * @param GenericEvent $event
  27.      */
  28.     public function initializeRequest(GenericEvent $event)
  29.     {
  30.         $request null;
  31.         if (null !== $this->requestStack) {
  32.             $request $this->requestStack->getCurrentRequest();
  33.         }
  34.         if (null === $request) {
  35.             return;
  36.         }
  37.         $request->attributes->set('easyadmin', [
  38.             'entity' => $entity $event->getArgument('entity'),
  39.             'view' => $request->query->get('action''list'),
  40.             'item' => (null !== $id $request->query->get('id')) ? $this->findCurrentItem($entity$id) : null,
  41.         ]);
  42.     }
  43.     /**
  44.      * Looks for the object that corresponds to the selected 'id' of the current entity.
  45.      *
  46.      * @param array $entityConfig
  47.      * @param mixed $itemId
  48.      *
  49.      * @return object The entity
  50.      *
  51.      * @throws EntityNotFoundException
  52.      * @throws \RuntimeException
  53.      */
  54.     private function findCurrentItem(array $entityConfig$itemId)
  55.     {
  56.         if (null === $manager $this->doctrine->getManagerForClass($entityConfig['class'])) {
  57.             throw new \RuntimeException(sprintf('There is no Doctrine Entity Manager defined for the "%s" class'$entityConfig['class']));
  58.         }
  59.         if (null === $entity $manager->getRepository($entityConfig['class'])->find($itemId)) {
  60.             throw new EntityNotFoundException(['entity_name' => $entityConfig['name'], 'entity_id_name' => $entityConfig['primary_key_field_name'], 'entity_id_value' => $itemId]);
  61.         }
  62.         return $entity;
  63.     }
  64. }