<?php
namespace App\Subscriber;
use App\Entity\JobOffer;
use App\Entity\Post;
use App\Service\JobOfferNewsletterSender;
use Doctrine\ORM\EntityManager;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\EventDispatcher\GenericEvent;
use Twig\Error\LoaderError;
use Twig\Error\RuntimeError;
use Twig\Error\SyntaxError;
class PostSubscriber implements EventSubscriberInterface
{
/**
* @var EntityManager
*/
public $em;
public function __construct($em)
{
$this->em = $em;
}
public static function getSubscribedEvents()
{
return array(
'easy_admin.post_persist' => array('afterCreated'),
'easy_admin.pre_update' => array('preUpdated'),
);
}
/**
* @param GenericEvent $event
* @throws LoaderError
* @throws RuntimeError
* @throws SyntaxError
*/
public function afterCreated(GenericEvent $event)
{
$entity = $event->getSubject();
if($entity instanceof Post) {
$em = $this->em;
$post = $entity;
$isMain = $post->getIsMain();
$createdPostId = $post->getId();
$previousMainPost = $em->getRepository(Post::class)->findOneBy(['isMain' => true ]);
if(isset($previousMainPost)) {
$notNewPost = ($previousMainPost->getId() !== $createdPostId);
if($isMain && $notNewPost) {
$previousMainPost->setIsMain(false);
$em->persist($previousMainPost);
}
$em->flush();
}
}
}
/**
* @param GenericEvent $event
* @throws LoaderError
* @throws RuntimeError
* @throws SyntaxError
*/
public function preUpdated(GenericEvent $event)
{
$entity = $event->getSubject();
if($entity instanceof Post) {
$this->afterCreated($event);
}
}
}