<?php
namespace App\EventSubscriber;
use ApiPlatform\Core\EventListener\EventPriorities;
use App\Entity\Undanews;
use App\Entity\UndanewsMediaObject;
use App\Exception\Api\UndanewsMediaObjectMaximumNumberException;
use App\Repository\UndanewsMediaObjectRepository;
use App\Repository\UndanewsRepository;
use App\Service\RemoveMediaObjectsNotLinkedService;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\Filesystem\Filesystem;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpKernel\Event\ViewEvent;
use Symfony\Component\HttpKernel\KernelEvents;
class CheckNumberUndanewsMediaObjectSubscriber implements EventSubscriberInterface
{
/**
* @var UndanewsMediaObjectRepository
*/
private $undanewsMediaObjectRepository;
/**
* @var UndanewsRepository
*/
private $undanewsRepository;
/**
* @var Filesystem
*/
private $filesystem;
/**
* @var RemoveMediaObjectsNotLinkedService
*/
private $removeMediaObjectsNotLinkedService;
public function __construct(UndanewsMediaObjectRepository $undanewsMediaObjectRepository,
UndanewsRepository $undanewsRepository, Filesystem $filesystem, RemoveMediaObjectsNotLinkedService $removeMediaObjectsNotLinkedService)
{
$this->undanewsMediaObjectRepository = $undanewsMediaObjectRepository;
$this->undanewsRepository = $undanewsRepository;
$this->filesystem = $filesystem;
$this->removeMediaObjectsNotLinkedService = $removeMediaObjectsNotLinkedService;
}
public static function getSubscribedEvents()
{
return [
KernelEvents::VIEW => ['checkNumberUndanewsMediaObject', EventPriorities::POST_WRITE],
];
}
/**
* @throws UndanewsMediaObjectMaximumNumberException
*/
public function checkNumberUndanewsMediaObject(ViewEvent $viewEvent)
{
$undanews = $viewEvent->getControllerResult();
$method = $viewEvent->getRequest()->getMethod();
if (!$undanews instanceof Undanews || (Request::METHOD_PUT !== $method && Request::METHOD_POST !== $method)) {
return;
}
$json_decode = json_decode($viewEvent->getRequest()->getContent(), true);
if(isset($json_decode['undanewsMediaObjects'])) {
$undanewsMediaObjetsRequest = $json_decode['undanewsMediaObjects'];
} else {
return;
}
$numberOfUndanewsMediaObjetsAssigned = $this->undanewsMediaObjectRepository->count(['undanews' => $undanews->getId()]);
/** @var UndanewsMediaObject $undanewsMediaObjetsNotAssigned */
$undanewsMediaObjetsNotAssigned = $this->undanewsMediaObjectRepository->findBy(['undanews' => null]);
/** @var UndanewsMediaObject $itemToRemove */
foreach ($undanewsMediaObjetsNotAssigned as $itemToRemove) {
$this->filesystem->remove($itemToRemove->getFile());
$this->undanewsMediaObjectRepository->remove($itemToRemove, true);
}
if (count($undanewsMediaObjetsRequest) > $numberOfUndanewsMediaObjetsAssigned) {
throw new UndanewsMediaObjectMaximumNumberException(sprintf('The undanews %s whith title %s has the maximum number of photos %s', $undanews->getId(), $undanews->getTitle(), count($undanews->getUndanewsMediaObjects())));
}
}
}