src/EventSubscriber/EasyAdminSubscriber.php line 77

Open in your IDE?
  1. <?php
  2. /**
  3.  * Created by PhpStorm.
  4.  * User: Rémi
  5.  * Date: 19/06/2020
  6.  * Time: 11:02
  7.  *
  8.  * Copyright 2018-2019, Rémi Fongaufier, All rights reserved.
  9.  */
  10. namespace App\EventSubscriber;
  11. use App\Entity\Attachment;
  12. use App\Entity\Collection;
  13. use App\Entity\Product;
  14. use App\Entity\Project;
  15. use App\Entity\Section;
  16. use App\Service\FilePathAndUrlService;
  17. use App\Service\LocaleService;
  18. use App\Traits\CustomSlugify;
  19. use Doctrine\ORM\EntityManagerInterface;
  20. use Gedmo\Translatable\TranslatableListener;
  21. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  22. use Symfony\Component\EventDispatcher\GenericEvent;
  23. use Symfony\Component\Filesystem\Exception\IOExceptionInterface;
  24. use Symfony\Component\Filesystem\Filesystem;
  25. use Symfony\Component\HttpFoundation\File\Exception\FileException;
  26. class EasyAdminSubscriber implements EventSubscriberInterface
  27. {
  28.     use CustomSlugify;
  29.     private $entityManager;
  30.     /**
  31.      * @var FilePathAndUrlService
  32.      */
  33.     private $filePathAndUrlService;
  34.     /**
  35.      * @var Filesystem
  36.      */
  37.     private $filesystem;
  38.     /**
  39.      * @var LocaleService
  40.      */
  41.     private $localeService;
  42.     /**
  43.      * @var TranslatableListener
  44.      */
  45.     private $projectDir;
  46.     public function __construct(EntityManagerInterface $entityManagerFilePathAndUrlService $filePathAndUrlService,
  47.                                 Filesystem $filesystemLocaleService $localeService$projectDir)
  48.     {
  49.         $this->entityManager $entityManager;
  50.         $this->filePathAndUrlService $filePathAndUrlService;
  51.         $this->filesystem $filesystem;
  52.         $this->localeService $localeService;
  53.         $this->projectDir $projectDir;
  54.     }
  55.     public static function getSubscribedEvents()
  56.     {
  57.         return [
  58.             'easy_admin.pre_update' => ['preUpdateInitAttachments'],
  59.             'easy_admin.pre_persist' => ['prePersistInitAttachments'],
  60.             'easy_admin.post_remove' => ['postRemoveEvent'],
  61.         ];
  62.     }
  63.     public function preUpdateInitAttachments(GenericEvent $event)
  64.     {
  65.         $this->renameSection($event);
  66.         $this->initAttachments($event);
  67.     }
  68.     public function prePersistInitAttachments(GenericEvent $event)
  69.     {
  70.         $this->renameSection($event);
  71.         $this->initAttachments($event);
  72.     }
  73.     public function postRemoveEvent(GenericEvent $event)
  74.     {
  75.         $this->renameSection($event);
  76.         $this->entityManager->flush();
  77.     }
  78.     public function initAttachments(GenericEvent $event)
  79.     {
  80.         $subject $event->getSubject();
  81.         if (!($subject instanceof Section || $subject instanceof Project
  82.             || $subject instanceof Product || $subject instanceof Collection))
  83.             return;
  84.         $currentObject strtolower(explode('\\'get_class($subject))[2]);
  85.         $attachmentsFromFile = [];
  86.         if ($event->getArguments()['request']->files->get('collection') !== null || $event->getArguments()['request']->files->get($currentObject) !== null) {
  87.             $attachmentsFromFile $event->getArguments()['request']->files->get('collection') !== null ?
  88.                 $event->getArguments()['request']->files->get('collection')['attachments'] :
  89.                 $event->getArguments()['request']->files->get($currentObject)['attachments'];
  90.         }
  91.         $attachmentsFromRequest = isset($event->getArguments()['request']->request->get($currentObject)['attachments']) ?
  92.             $event->getArguments()['request']->request->get($currentObject)['attachments'] : [];
  93.         foreach ($attachmentsFromFile as $id => $el) {
  94.             if ($el['image'] !== null) {
  95.                 if (isset($attachmentsFromRequest[$id]) && $this->entityManager->getRepository(Attachment::class)->find($attachmentsFromRequest[$id]['id'])) {
  96.                     $attachment $this->entityManager->getRepository(Attachment::class)->find($attachmentsFromRequest[$id]['id']);
  97.                     if (!$this->filesystem->exists($this->projectDir '/public/' $attachment->getFullPath()))
  98.                         $attachment->setId(null);
  99.                 } else {
  100.                     $attachment = new Attachment();
  101.                 }
  102.                 $file $el['image'];
  103.                 $fileName $this->filePathAndUrlService->getFileName($subject$file);
  104.                 $path $this->filePathAndUrlService->getFilePath($subject);
  105.                 $attachment->setName($fileName);
  106.                 $attachment->setPath($path);
  107.                 $attachment->setSize($file->getSize());
  108.                 $attachment->setToShow(isset($attachmentsFromRequest[$id]['toShow']) ? $attachmentsFromRequest[$id]['toShow'] :
  109.                     (isset($event->getArguments()['request']->request->get('collection')['attachments'][$id]['toShow']) ?
  110.                         $event->getArguments()['request']->request->get('collection')['attachments'][$id]['toShow'] : false)
  111.                 );
  112.                 $attachment->setId((int)$id);
  113.                 if ($subject instanceof Product)
  114.                     $attachment->setProduct($subject);
  115.                 if ($subject instanceof Project)
  116.                     $attachment->setProject($subject);
  117.                 if ($subject instanceof Collection)
  118.                     $attachment->setCollection($subject);
  119.                 if ($subject instanceof Section)
  120.                     $attachment->setSection($subject);
  121.                 $subject->addAttachment($attachment);
  122.                 //$this->entityManager->persist($attachment);
  123.                 if (isset($event->getArguments()['request']->request->get('collection')['attachments'][$id]['caption']))
  124.                     $attachment->setCaption($event->getArguments()['request']->request->get('collection')['attachments'][$id]['caption']);
  125.                 try {
  126.                     if (!$this->filesystem->exists($this->projectDir '/public/' $attachment->getPath()))
  127.                         $this->filesystem->mkdir($this->projectDir '/public/' $attachment->getPath(), 0777);
  128.                     $file->move(
  129.                         $this->projectDir '/public/' $attachment->getPath(),
  130.                         $attachment->getName()
  131.                     );
  132.                 } catch (FileException IOExceptionInterface $e) {
  133.                     dd($e->getMessage());
  134.                 }
  135.             }
  136.         }
  137.         $this->saveSubjectTranslations($subject);
  138.         $attachments $subject->getAttachments()->getValues();
  139.         foreach ($attachments as $index => $attachment) {
  140.             if ($attachment->getId() === null || !$this->filesystem->exists($this->projectDir '/public/' $attachment->getFullPath())
  141.                 || $attachment->getName() === null) {
  142.                 $subject->removeAttachment($attachment);
  143.                 /*$this->entityManager->remove($attachment);*/
  144.                 unset($attachments[$index]);
  145.             }
  146.         }
  147.         $this->localeService->saveFieldTranslationsFromEntities($attachments'caption');
  148.         if ($subject instanceof Product) {
  149.             $name $subject->getName();
  150.             $slug $this->slugify($name);
  151.             $subject->setSlug($slug);
  152.         }
  153.         $this->entityManager->persist($subject);
  154.         $this->entityManager->flush();
  155.     }
  156.     public function removeAttachment($attachment$subject)
  157.     {
  158.         $subject->removeAttachment($attachment);
  159.         $this->entityManager->detach($attachment);
  160.         if ($attachment->getId()) {
  161.             $conn $this->entityManager->getConnection();
  162.             $sql "DELETE FROM `ext_translations` " .
  163.                 "WHERE `object_class` = 'App\\Entity\\Attachment' and `foreign_key` = " $attachment->getId();
  164.             $stmt $conn->prepare($sql);
  165.             $stmt->execute();
  166.             $sql "DELETE FROM `attachment` WHERE `id` = " $attachment->getId();
  167.             $stmt $conn->prepare($sql);
  168.             $stmt->execute();
  169.         }
  170.     }
  171.     public function saveSubjectTranslations($subject)
  172.     {
  173.         if ($subject instanceof Product) {
  174.             $this->localeService->saveFieldTranslationsFromEntity($subject'description');
  175.         }
  176.         if ($subject instanceof Project) {
  177.             $this->localeService->saveFieldTranslationsFromEntity($subject'description');
  178.         }
  179.         if ($subject instanceof Collection) {
  180.             $this->localeService->saveFieldTranslationsFromEntity($subject'description');
  181.         }
  182.         if ($subject instanceof Section) {
  183.             $slugs = [];
  184.             foreach ($subject->getDesignation() as $key => $designation) {
  185.                 $slugs[$key] = $this->slugify($designation);
  186.             }
  187.             $subject->setName("Section " . (count($subject->getSeoPage()->getSections()) + 1));
  188.             $subject->setSlug($slugs);
  189.             $this->localeService->saveFieldTranslationsFromEntity($subject'slug');
  190.             $this->localeService->saveFieldTranslationsFromEntity($subject'designation');
  191.             $this->localeService->saveFieldTranslationsFromEntity($subject'content');
  192.         }
  193.     }
  194.     public function renameSection($event)
  195.     {
  196.         $subject $event->getSubject();
  197.         if ($subject instanceof Section) {
  198.             if ($subject->getSeoPage()) {
  199.                 $seoPage $subject->getSeoPage();
  200.                 $sections $seoPage->getSections();
  201.                 if (isset($seoPage)) {
  202.                     foreach ($sections as $index => $section) {
  203.                         $section->setName("Section " . ($index 1));
  204.                         if ($section->getId() === $subject->getId())
  205.                             $subject->setName("Section " . ($index 1));
  206.                         $this->entityManager->persist($section);
  207.                     }
  208.                 }
  209.             }
  210.         }
  211.     }
  212. }