vendor/roothirsch/declaration-bundle/EventSubscriber/DeclarationDuplicateSubscriber.php line 38

Open in your IDE?
  1. <?php
  2. namespace Roothirsch\DeclarationBundle\EventSubscriber;
  3. use ApiPlatform\Core\EventListener\EventPriorities;
  4. use Roothirsch\DeclarationBundle\Repository\DeclarationRepository;
  5. use Doctrine\Common\Collections\ArrayCollection;
  6. use Doctrine\ORM\EntityManagerInterface;
  7. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  8. use Symfony\Component\HttpKernel\KernelEvents;
  9. final class DeclarationDuplicateSubscriber implements EventSubscriberInterface
  10. {
  11.     /**
  12.      * @var DeclarationRepository
  13.      */
  14.     private $declarationRepository;
  15.     /**
  16.      * @var EntityManagerInterface
  17.      */
  18.     private $entityManager;
  19.     public function __construct(DeclarationRepository $declarationRepositoryEntityManagerInterface $entityManager)
  20.     {
  21.         $this->declarationRepository $declarationRepository;
  22.         $this->entityManager $entityManager;
  23.     }
  24.     public static function getSubscribedEvents()
  25.     {
  26.         return [
  27.             KernelEvents::VIEW => ['validate'EventPriorities::PRE_VALIDATE],
  28.         ];
  29.     }
  30.     public function validate(\Symfony\Component\HttpKernel\Event\ViewEvent $event)
  31.     {
  32.         if ($event->getRequest()->attributes->get('_route') === 'api_declarations_duplicate_collection') {
  33.             /** @var \Roothirsch\DeclarationBundle\Entity\Declaration $duplicate */
  34.             $duplicate = clone $this->declarationRepository->find($event->getRequest()->attributes->get('id'));
  35.             $duplicate->setCreatedAt(null);
  36.             $duplicate->setId(null);
  37.             $usages $duplicate->getUsages();
  38.             $duplicate->setUsages(new ArrayCollection());
  39.             foreach ($usages as $usage) {
  40.                 /** @var \Roothirsch\DeclarationBundle\Entity\Usage $usageDuplicate */
  41.                 $usageDuplicate = clone $usage;
  42.                 $usageDuplicate->setId(null);
  43.                 $this->entityManager->persist($usageDuplicate);
  44.                 $duplicate->addUsage($usageDuplicate);
  45.             }
  46.             $event->setControllerResult($duplicate);
  47.         }
  48.     }
  49. }