src/EventSubscriber/AudioSubscriber.php line 35

Open in your IDE?
  1. <?php
  2. namespace App\EventSubscriber;
  3. use App\Entity\AudioInterface;
  4. use Boab\CmsBundle\Contract\FileUploaderInterface;
  5. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  6. use Boab\CmsBundle\Event\ContentPrePersistEvent;
  7. use Boab\CmsBundle\Event\ContentPreUpdateEvent;
  8. use Symfony\Component\HttpFoundation\File\UploadedFile;
  9. class AudioSubscriber implements EventSubscriberInterface
  10. {
  11.     private $fileUploader;
  12.     public function __construct(FileUploaderInterface $fileUploader)
  13.     {
  14.         $this->fileUploader $fileUploader;
  15.     }
  16.     
  17.     public function onContentPrePersist(ContentPrePersistEvent $event)
  18.     {
  19.         if(!$event->getEntity() instanceof AudioInterface){
  20.             return;
  21.         }
  22.         $primaryFile $event->getForm()->get("primaryFile")->getData();
  23.         if(!$primaryFile instanceof UploadedFile){
  24.             return;
  25.         }
  26.         $entity $event->getEntity();
  27.         $this->uploadAudio($entity$primaryFile);
  28.     }
  29.     public function onContentPreUpdate(ContentPreUpdateEvent $event)
  30.     {
  31.         if(!$event->getEntity() instanceof AudioInterface){
  32.             return;
  33.         }
  34.         $primaryFile $event->getForm()->get("primaryFile")->getData();
  35.         if(!$primaryFile instanceof UploadedFile){
  36.             return;
  37.         }
  38.         $entity $event->getEntity();
  39.         $this->uploadAudio($entity$primaryFile);
  40.     }
  41.     private function uploadAudio($entity$primaryFile)
  42.     {
  43.         $oldPrimaryFile $entity->getPrimaryFile();
  44.         $fileName $this->fileUploader->upload($primaryFile$entity->getUploadRoot());
  45.         $entity->setPrimaryFile($fileName);
  46.         $this->fileUploader->delete($oldPrimaryFile);  
  47.     }
  48.     public static function getSubscribedEvents()
  49.     {
  50.         return [
  51.             'content.pre_persist' => 'onContentPrePersist',
  52.             'content.pre_update' => 'onContentPreUpdate',
  53.         ];
  54.     }
  55. }