<?php
namespace Boab\CmsBundle\EventListener;
use Boab\CmsBundle\Contract\FileUploaderInterface;
use Boab\CmsBundle\Entity\PhotoInterface;
use Boab\CmsBundle\Event\PhotoDeleteEvent;
use Boab\CmsBundle\Event\EntityEvent;
use Symfony\Component\HttpFoundation\File\UploadedFile;
class PhotoManagerListener
{
private $fileUploader;
public function __construct(FileUploaderInterface $fileUploader)
{
$this->fileUploader = $fileUploader;
}
public function onPhotoCreate(EntityEvent $event):void
{
$entity = $event->getEntity();
$uploadedFile = $entity->getUploadedFile();
if(!$entity instanceof PhotoInterface || !$uploadedFile instanceof UploadedFile){
return;
}
$newFileName = $this->fileUploader->upload($uploadedFile, $entity->getUploadRoot());
$entity->setFileName($newFileName);
}
public function onPhotoDelete(PhotoDeleteEvent $event)
{
$entity = $event->getEntity();
$thumbnailFile = $entity->getUploadRoot().'/'.$entity->getFileName();
$this->fileUploader->delete($thumbnailFile);
}
}