<?php
namespace App\EventListener;
use App\Entity\Central\Storage\Image;
use App\Entity\ImagesAwareInterface;
use App\Service\Uploader\ImageUploader;
use Symfony\Component\EventDispatcher\GenericEvent;
use Webmozart\Assert\Assert;
class ImagesUploadListener
{
/** @var ImageUploader */
private $uploader;
public function __construct(ImageUploader $uploader)
{
$this->uploader = $uploader;
}
public function uploadImages(GenericEvent $event): void
{
$subject = $event->getSubject();
Assert::isInstanceOf($subject, ImagesAwareInterface::class);
$this->uploadSubjectImages($subject);
}
public function uploadImage(GenericEvent $event): void
{
$image = $event->getSubject();
Assert::isInstanceOf($image, Image::class);
if ($image->hasFile()) {
$this->uploader->upload($image);
}
}
private function uploadSubjectImages(ImagesAwareInterface $subject): void
{
$images = $subject->getImages();
foreach ($images as $image) {
if ($image->hasFile()) {
$this->uploader->upload($image);
} elseif($image->getBase64() !== null){
$this->uploader->uploadBase64($image);
}
// Upload failed? Let's remove that image.
if (null === $image->getPath()) {
$images->removeElement($image);
}
}
}
}