src/Subscriber/PostSubscriber.php line 79

Open in your IDE?
  1. <?php
  2. namespace App\Subscriber;
  3. use App\Entity\JobOffer;
  4. use App\Entity\Post;
  5. use App\Service\JobOfferNewsletterSender;
  6. use Doctrine\ORM\EntityManager;
  7. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  8. use Symfony\Component\EventDispatcher\GenericEvent;
  9. use Twig\Error\LoaderError;
  10. use Twig\Error\RuntimeError;
  11. use Twig\Error\SyntaxError;
  12. class PostSubscriber implements EventSubscriberInterface
  13. {
  14.     /**
  15.      *  @var EntityManager
  16.      */
  17.     public $em;
  18.     public function __construct($em)
  19.     {
  20.         $this->em $em;
  21.     }
  22.     public static function getSubscribedEvents()
  23.     {
  24.         return array(
  25.             'easy_admin.post_persist' => array('afterCreated'),
  26.             'easy_admin.pre_update' => array('preUpdated'),
  27.         );
  28.     }
  29.     /**
  30.      * @param GenericEvent $event
  31.      * @throws LoaderError
  32.      * @throws RuntimeError
  33.      * @throws SyntaxError
  34.      */
  35.     public function afterCreated(GenericEvent $event)
  36.     {
  37.         $entity $event->getSubject();
  38.         if($entity instanceof Post) {
  39.             $em $this->em;
  40.             $post $entity;
  41.             $isMain $post->getIsMain();
  42.             $createdPostId $post->getId();
  43.             $previousMainPost $em->getRepository(Post::class)->findOneBy(['isMain' => true ]);
  44.             if(isset($previousMainPost)) {
  45.                 $notNewPost = ($previousMainPost->getId() !== $createdPostId);
  46.                 if($isMain && $notNewPost) {
  47.                     $previousMainPost->setIsMain(false);
  48.                     $em->persist($previousMainPost);
  49.                 }
  50.                 $em->flush();
  51.             }
  52.         }
  53.     }
  54.     /**
  55.      * @param GenericEvent $event
  56.      * @throws LoaderError
  57.      * @throws RuntimeError
  58.      * @throws SyntaxError
  59.      */
  60.     public function preUpdated(GenericEvent $event)
  61.     {
  62.         $entity $event->getSubject();
  63.         if($entity instanceof Post) {
  64.             $this->afterCreated($event);
  65.         }
  66.     }
  67. }