<?php
namespace App\EventSubscriber;
use ApiPlatform\Core\EventListener\EventPriorities;
use App\Entity\Undanita;
use App\Entity\UndanitaMediaObject;
use App\Exception\Api\UndanitaMediaObjectMaximumNumberException;
use App\Repository\UndanitaMediaObjectRepository;
use phpDocumentor\Reflection\DocBlock\Tags\Return_;
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 CheckNumberUndanitaMediaObjectSubscriber implements EventSubscriberInterface
{
/**
* @var UndanitaMediaObjectRepository
*/
private $undanitaMediaObjectRepository;
/**
* @var Filesystem
*/
private $filesystem;
public function __construct(UndanitaMediaObjectRepository $undanitaMediaObjectRepository, Filesystem $filesystem)
{
$this->undanitaMediaObjectRepository = $undanitaMediaObjectRepository;
$this->filesystem = $filesystem;
}
public static function getSubscribedEvents()
{
return [
KernelEvents::VIEW => ['checkNumberUndanitaMediaObject', EventPriorities::POST_WRITE],
];
}
/**
* @throws UndanitaMediaObjectMaximumNumberException
*/
public function checkNumberUndanitaMediaObject(ViewEvent $viewEvent)
{
$undanita = $viewEvent->getControllerResult();
$method = $viewEvent->getRequest()->getMethod();
if (!$undanita instanceof Undanita || (Request::METHOD_PUT !== $method && Request::METHOD_POST !== $method)) {
return;
}
$json_decode = json_decode($viewEvent->getRequest()->getContent(), true);
if(isset($json_decode['undanitaMediaObjects'])) {
$undanitaMediaObjetsRequest = $json_decode['undanitaMediaObjects'];
} else {
return;
}
$numberOfUndanitaMediaObjetsAssigned = $this->undanitaMediaObjectRepository->count(['undanita' => $undanita->getId()]);
/** @var UndanitaMediaObject $undanitaMediaObjetsNotAssigned */
$undanitaMediaObjetsNotAssigned = $this->undanitaMediaObjectRepository->findBy(['undanita' => null]);
/** @var UndanitaMediaObject $itemToRemove */
foreach ($undanitaMediaObjetsNotAssigned as $itemToRemove) {
$this->filesystem->remove($itemToRemove->getFile());
$this->undanitaMediaObjectRepository->remove($itemToRemove, true);
}
if (count($undanitaMediaObjetsRequest) > $numberOfUndanitaMediaObjetsAssigned) {
throw new UndanitaMediaObjectMaximumNumberException(sprintf('The undanita %s whith title %s has the maximum number of photos %s', $undanita->getId(), $undanita->getTitle(), count($undanita->getUndanitaMediaObjects())));
}
}
}