src/EventSubscriber/EasyAdminSubscriber.php line 47

Open in your IDE?
  1. <?php
  2. namespace App\EventSubscriber;
  3. use App\Entity\Product;
  4. use Symfony\Component\HttpKernel\KernelInterface;
  5. use Symfony\Component\HttpFoundation\File\UploadedFile;
  6. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  7. use EasyCorp\Bundle\EasyAdminBundle\Event\BeforeEntityUpdatedEvent;
  8. use EasyCorp\Bundle\EasyAdminBundle\Event\BeforeEntityPersistedEvent;
  9. class EasyAdminSubscriber implements EventSubscriberInterface
  10. {
  11. private $appKernel;
  12. public function __construct(KernelInterface $appKernel){
  13. $this->appKernel = $appKernel;
  14. }
  15. public static function getSubscribedEvents() {
  16. return [
  17. BeforeEntityPersistedEvent::class => ['setIllustration'],
  18. BeforeEntityUpdatedEvent::class => ['updateIllustration'],
  19. ];
  20. }
  21. public function uploadIllustration($event){
  22. $entity = $event->getEntityInstance();
  23. $illustrationFile = isset($_FILES['Product']['tmp_name']['illustration']);
  24. if (!$illustrationFile instanceof UploadedFile) {
  25. return;
  26. }
  27. $tmpName = $illustrationFile->getPathname();
  28. $filename = uniqid();
  29. $extension = $illustrationFile->getClientOriginalExtension();
  30. $projectDir = $this->appKernel->getProjectDir();
  31. move_uploaded_file($tmpName, $projectDir.'/public/uploads/'.$filename.'.'.$extension);
  32. $entity->setIllustration($filename.'.'.$extension);
  33. }
  34. public function updateIllustration(BeforeEntityUpdatedEvent $event)
  35. {
  36. $illustrationFile = isset($_FILES['Product']['tmp_name']['illustration']);
  37. if(!($event->getEntityInstance() instanceof Product)){
  38. if ($illustrationFile && $_FILES['Product']['tmp_name']['illustration'] != '') {
  39. $this->uploadIllustration($event);
  40. }
  41. }
  42. }
  43. public function setIllustration(BeforeEntityPersistedEvent $event)
  44. {
  45. if(!($event->getEntityInstance() instanceof Product)){
  46. $this->uploadIllustration($event);
  47. }
  48. }
  49. }