src/Listener/ModelManagerExceptionResponseListener.php line 25

Open in your IDE?
  1. <?php
  2. namespace App\EventListener;
  3. use Symfony\Component\HttpFoundation\Session\SessionInterface;
  4. use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
  5. use Doctrine\ORM\EntityManagerInterface;
  6. use Symfony\Component\HttpKernel\Event\ExceptionEvent;
  7. use Symfony\Component\HttpFoundation\RedirectResponse;
  8. use Sonata\AdminBundle\Exception\ModelManagerException;
  9. class ModelManagerExceptionResponseListener
  10. {
  11.     private $session;
  12.     private $router;
  13.     private $em;
  14.     public function __construct(SessionInterface $sessionUrlGeneratorInterface $routerEntityManagerInterface $em)
  15.     {
  16.         $this->session $session;
  17.         $this->router $router;
  18.         $this->em $em;
  19.     }
  20.     public function onKernelException(ExceptionEvent $event)
  21.     {
  22.         // get the exception
  23.         $exception =  $event->getThrowable();
  24.         // we proceed only if it is ModelManagerException
  25.         if (!$exception instanceof ModelManagerException) {
  26.             return;
  27.         }
  28.         // get the route and id
  29.         // if it wasn't a delete route we don't want to proceed
  30.         $request $event->getRequest();
  31.         $route $request->get('_route');
  32.         $id $request->get('id');
  33.         if (substr($route, -6) !== 'delete') {
  34.             return;
  35.         }
  36.         $route str_replace('delete''edit'$route);
  37.         // get the message
  38.         // we proceed only if it is the desired message
  39.         $message $exception->getMessage();
  40.         $failure 'Failed to delete object: ';
  41.         if (strpos($message$failure) < 0) {
  42.             return;
  43.         }
  44.         // get the object that can't be deleted
  45.         $entity str_replace($failure''$message);
  46.         $repository $this->em->getRepository($entity);
  47.         $object $repository->findOneById($id);
  48.         $this->session->getFlashBag()
  49.             ->add(
  50.                 'sonata_flash_error',
  51.                 sprintf('L\'élément "%s" ne peut pas être effacé car il est utilisé dans certaines demandes.'$object)
  52.             )
  53.         ;
  54.         // redirect to the edit form of the object
  55.         $url $this->router->generate($route, ['id' => $id]);
  56.         $response = new RedirectResponse($url);
  57.         $event->setResponse($response);
  58.     }
  59. }