<?php
namespace App\EventSubscriber;
use App\Entity\Image;
use App\Entity\Menu;
use App\Entity\Restaurante;
use EasyCorp\Bundle\EasyAdminBundle\Event\BeforeEntityPersistedEvent;
use EasyCorp\Bundle\EasyAdminBundle\Event\BeforeEntityUpdatedEvent;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\Security\Core\Security;
class AdminSubscriber implements EventSubscriberInterface
{
private Security $security;
public function __construct(Security $security)
{
$this->security = $security;
}
public static function getSubscribedEvents()
{
return [
BeforeEntityUpdatedEvent::class => ['onUpdatedsetImageUser'],
BeforeEntityPersistedEvent::class => ['onPersistedsetImageUser'],
];
}
public function onUpdatedsetImageUser(BeforeEntityUpdatedEvent $event)
{
$entity = $event->getEntityInstance();
if ($entity instanceof Menu) {
$user = $entity->getRestaurante()->getUser();
$images = $entity->getImages();
$this->updateImages($images,$user);
} elseif ($entity instanceof Restaurante) {
$user = $entity->getUser();
$images = $entity->getImages();
$this->updateImages($images,$user);
}
return;
}
public function onPersistedsetImageUser(BeforeEntityPersistedEvent $event)
{
$entity = $event->getEntityInstance();
if ($entity instanceof Menu) {
$user = $entity->getRestaurante()->getUser();
$images = $entity->getImages();
$this->updateImages($images,$user);
} elseif ($entity instanceof Restaurante) {
$user = $entity->getUser();
$images = $entity->getImages();
$this->updateImages($images,$user);
}
return;
}
public function updateImages($images,$user){
foreach ($images as $image) {
if($image->getFile()){
$image->setFilepath('');
}
$image->setUser($user);
}
}
}