<?php
namespace Boab\CmsBundle\EventListener;
use Boab\CmsBundle\Event\EntityEvent;
use Boab\CmsBundle\Util\FileUploader;
use Boab\CmsBundle\Event\TermPrePersistEvent;
use Boab\CmsBundle\Entity\FileUploadInterface;
use Boab\CmsBundle\Event\ContentPreUpdateEvent;
use Symfony\Component\HttpFoundation\File\UploadedFile;
use Boab\CmsBundle\Event\ContentPrePersistEvent;
use Boab\CmsBundle\Entity\PhotoInterface;
use Symfony\Component\HttpFoundation\File\File;
class FileUploadListener
{
private $fileUploader;
public function __construct(FileUploader $fileUploader)
{
$this->fileUploader = $fileUploader;
}
public function onPrePersist(ContentPrePersistEvent $event)
{
$entity = $event->getEntity();
if(!$entity instanceof FileUploadInterface){
return;
}
$this->saveFile($entity);
}
public function onPreUpdate(ContentPreUpdateEvent $event)
{
$entity = $event->getEntity();
if(!$entity instanceof FileUploadInterface){
return;
}
$this->saveFile($entity);
}
public function onPrePersistTerm(TermPrePersistEvent $event)
{
$entity = $event->getTerm();
if(!$entity instanceOf FileUploadInterface){
return;
}
$this->saveFile($entity);
}
public function onPhotoCreate(EntityEvent $event) : void
{
$entity = $event->getEntity();
$photo = $entity->getUploadedFile();
if(!$entity instanceof PhotoInterface || !$photo instanceof UploadedFile){
return ;
}
$oldFileName = $entity->getFileName();
$file = $entity->getUploadedFile();
$newFileName = $this->fileUploader->upload($file, $entity->getUploadRoot());
$entity->setFileName($newFileName);
$oldThumbnail = $entity->getUploadRoot().'/'.$oldFileName;
$this->fileUploader->deleteFile($oldThumbnail);
}
private function saveFile(FileUploadInterface $entity)
{
$uploadedFile = $entity->getUploadedFile();
if($uploadedFile instanceof UploadedFile){
$oldThumbnail = $entity->getThumbnailPath();
/*
if(!$this->isDefaultThumbnail($oldThumbnail)){
$oldFile = $oldThumbnail->getPathname();
$this->fileUploader->deleteFile($oldFile);
}
*/
$destination = $entity->getUploadRoot();
$fileName = $this->fileUploader->upload($uploadedFile, $destination);
$entity->setThumbnail($fileName);
return;
}
/**
* Reset thumbnail to normal filename and ignore default thumbnail
*/
$thumbnail = $entity->getThumbnail();
$fileName = $thumbnail instanceof File ? $thumbnail->getBasename() : $thumbnail;
if($fileName == FileUploader::DEFAULT_THUMBNAIL){
$entity->setThumbnail(null);
return;
}
$entity->setThumbnail($fileName);
}
}