src/EventSubscriber/ItemDocumentDeleteEventSubscriber.php line 39

  1. <?php
  2. declare(strict_types=1);
  3. namespace App\EventSubscriber;
  4. use ApiPlatform\Core\EventListener\EventPriorities;
  5. use App\Entity\ItemDocument;
  6. use App\Entity\ItemDocumentIndicator;
  7. use App\Entity\ItemDocumentReport;
  8. use App\Enum\ReportStatusEnum;
  9. use App\Repository\ItemDocumentIndicatorRepository;
  10. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  11. use Symfony\Component\Filesystem\Filesystem;
  12. use Symfony\Component\HttpFoundation\JsonResponse;
  13. use Symfony\Component\HttpFoundation\Request;
  14. use Symfony\Component\HttpFoundation\Response;
  15. use Symfony\Component\HttpKernel\Event\ViewEvent;
  16. use Symfony\Component\HttpKernel\KernelEvents;
  17. use Symfony\Contracts\Translation\TranslatorInterface;
  18. final class ItemDocumentDeleteEventSubscriber implements EventSubscriberInterface
  19. {
  20.     public function __construct(
  21.         private readonly ItemDocumentIndicatorRepository $documentIndicatorRepository,
  22.         private readonly TranslatorInterface $translator,
  23.         private readonly Filesystem $filesystem
  24.     )
  25.     {
  26.     }
  27.     public static function getSubscribedEvents(): array
  28.     {
  29.         return [
  30.             KernelEvents::VIEW => ['unlinkDocument'EventPriorities::PRE_WRITE]
  31.         ];
  32.     }
  33.     public function unlinkDocument(ViewEvent $event): void
  34.     {
  35.         $entity $event->getControllerResult();
  36.         if (
  37.             !$entity instanceof ItemDocument
  38.             ||
  39.             Request::METHOD_DELETE !== $event->getRequest()->getMethod()
  40.         ) {
  41.             return;
  42.         }
  43.         $itemDocumentIndicators $this->documentIndicatorRepository->findBy(['itemDocument' => $entity]);
  44.         /** @var ItemDocumentIndicator $itemDocumentsIndicator */
  45.         foreach ($itemDocumentIndicators as $itemDocumentIndicator) {
  46.             if (null !== $itemDocumentIndicator->getValue()) {
  47.                 $event->setResponse(new JsonResponse(
  48.                     [
  49.                         'message' => $this->translator->trans('programs.project.itemDocument.indicatorValueDeleteError')
  50.                     ],
  51.                     Response::HTTP_UNPROCESSABLE_ENTITY
  52.                 ));
  53.             }
  54.         }
  55.         $this->filesystem->remove($entity->getFullDocumentPath());
  56.     }
  57. }