<?php
declare(strict_types=1);
namespace App\EventListener;
use App\Entity\FreeOption\FreeOption;
use App\Files\Uploader\FreeOptionUploader;
use Doctrine\ORM\EntityManager;
use Symfony\Component\EventDispatcher\GenericEvent;
final class FreeOptionListener
{
private FreeOptionUploader $freeOptionUploader;
private EntityManager $em;
public function __construct(FreeOptionUploader $freeOptionUploader, EntityManager $em)
{
$this->freeOptionUploader = $freeOptionUploader;
$this->em = $em;
}
public function preCreate(GenericEvent $event): void
{
/** @var FreeOption $freeOption */
$freeOption = $event->getSubject();
$file = $freeOption->getFile();
if (null === $file) {
return;
}
$pathFile = $this->freeOptionUploader->upload($file);
$freeOption->setFilePath($pathFile);
$this->em->persist($freeOption);
$this->em->flush();
}
public function preUpdate(GenericEvent $event): void
{
/** @var FreeOption $freeOption */
$freeOption = $event->getSubject();
$file = $freeOption->getFile();
$pathFile = $this->freeOptionUploader->upload($file);
$freeOption->setFilePath($pathFile);
$this->em->persist($freeOption);
$this->em->flush();
}
public function deleteFile(GenericEvent $event)
{
$subject = $event->getSubject();
if ($subject) {
$oldFilePath = $subject->getFilePath();
if (!empty($oldFilePath)) {
@unlink($oldFilePath);
}
}
}
}