src/EventSubscriber/EasyAdminSubscriber.php line 58

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.   
  12.    private $appKernel;
  13.    public function __construct(KernelInterface $appKernel){
  14.         $this->appKernel $appKernel;
  15.    }
  16.    
  17.     public static function getSubscribedEvents() {
  18.         return [
  19.             BeforeEntityPersistedEvent::class => ['setIllustration'],
  20.             BeforeEntityUpdatedEvent::class => ['updateIllustration'],
  21.         ];
  22.     }   
  23.     
  24.     public function uploadIllustration($event){
  25.         $entity $event->getEntityInstance();
  26.         
  27.         $illustrationFile = isset($_FILES['Product']['tmp_name']['illustration']);
  28.         
  29.         if (!$illustrationFile instanceof UploadedFile) {
  30.             return;
  31.         }
  32.         $tmpName $illustrationFile->getPathname();
  33.         $filename uniqid();
  34.         $extension $illustrationFile->getClientOriginalExtension(); 
  35.         $projectDir $this->appKernel->getProjectDir();
  36.         move_uploaded_file($tmpName$projectDir.'/public/uploads/'.$filename.'.'.$extension);
  37.         $entity->setIllustration($filename.'.'.$extension);
  38.     }
  39.     
  40.     public function updateIllustration(BeforeEntityUpdatedEvent $event)
  41.     {           
  42.         $illustrationFile = isset($_FILES['Product']['tmp_name']['illustration']);
  43.        
  44.         if(!($event->getEntityInstance() instanceof Product)){
  45.             if ($illustrationFile && $_FILES['Product']['tmp_name']['illustration'] != '') {
  46.                 $this->uploadIllustration($event);
  47.             }        
  48.         }   
  49.     }
  50.     
  51.     public function setIllustration(BeforeEntityPersistedEvent $event)
  52.     {
  53.         if(!($event->getEntityInstance() instanceof Product)){
  54.             $this->uploadIllustration($event); 
  55.         }   
  56.     }
  57. }