<?php
namespace App\EventSubscriber;
use App\Entity\AudioInterface;
use Boab\CmsBundle\Contract\FileUploaderInterface;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Boab\CmsBundle\Event\ContentPrePersistEvent;
use Boab\CmsBundle\Event\ContentPreUpdateEvent;
use Symfony\Component\HttpFoundation\File\UploadedFile;
class AudioSubscriber implements EventSubscriberInterface
{
private $fileUploader;
public function __construct(FileUploaderInterface $fileUploader)
{
$this->fileUploader = $fileUploader;
}
public function onContentPrePersist(ContentPrePersistEvent $event)
{
if(!$event->getEntity() instanceof AudioInterface){
return;
}
$primaryFile = $event->getForm()->get("primaryFile")->getData();
if(!$primaryFile instanceof UploadedFile){
return;
}
$entity = $event->getEntity();
$this->uploadAudio($entity, $primaryFile);
}
public function onContentPreUpdate(ContentPreUpdateEvent $event)
{
if(!$event->getEntity() instanceof AudioInterface){
return;
}
$primaryFile = $event->getForm()->get("primaryFile")->getData();
if(!$primaryFile instanceof UploadedFile){
return;
}
$entity = $event->getEntity();
$this->uploadAudio($entity, $primaryFile);
}
private function uploadAudio($entity, $primaryFile)
{
$oldPrimaryFile = $entity->getPrimaryFile();
$fileName = $this->fileUploader->upload($primaryFile, $entity->getUploadRoot());
$entity->setPrimaryFile($fileName);
$this->fileUploader->delete($oldPrimaryFile);
}
public static function getSubscribedEvents()
{
return [
'content.pre_persist' => 'onContentPrePersist',
'content.pre_update' => 'onContentPreUpdate',
];
}
}