<?php
namespace Roothirsch\DeclarationBundle\EventSubscriber;
use ApiPlatform\Core\EventListener\EventPriorities;
use Roothirsch\DeclarationBundle\Repository\DeclarationRepository;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpKernel\KernelEvents;
final class DeclarationDuplicateSubscriber implements EventSubscriberInterface
{
/**
* @var DeclarationRepository
*/
private $declarationRepository;
/**
* @var EntityManagerInterface
*/
private $entityManager;
public function __construct(DeclarationRepository $declarationRepository, EntityManagerInterface $entityManager)
{
$this->declarationRepository = $declarationRepository;
$this->entityManager = $entityManager;
}
public static function getSubscribedEvents()
{
return [
KernelEvents::VIEW => ['validate', EventPriorities::PRE_VALIDATE],
];
}
public function validate(\Symfony\Component\HttpKernel\Event\ViewEvent $event)
{
if ($event->getRequest()->attributes->get('_route') === 'api_declarations_duplicate_collection') {
/** @var \Roothirsch\DeclarationBundle\Entity\Declaration $duplicate */
$duplicate = clone $this->declarationRepository->find($event->getRequest()->attributes->get('id'));
$duplicate->setCreatedAt(null);
$duplicate->setId(null);
$usages = $duplicate->getUsages();
$duplicate->setUsages(new ArrayCollection());
foreach ($usages as $usage) {
/** @var \Roothirsch\DeclarationBundle\Entity\Usage $usageDuplicate */
$usageDuplicate = clone $usage;
$usageDuplicate->setId(null);
$this->entityManager->persist($usageDuplicate);
$duplicate->addUsage($usageDuplicate);
}
$event->setControllerResult($duplicate);
}
}
}