src/Hitso/Bundle/ContentBundle/EventListener/CommentListener.php line 25

Open in your IDE?
  1. <?php
  2. declare(strict_types=1);
  3. namespace Hitso\Bundle\ContentBundle\EventListener;
  4. use Hitso\Bundle\CommonBundle\Doctrine\Event\EntityEvent;
  5. use Hitso\Bundle\CommonBundle\Entity\User;
  6. use Hitso\Bundle\ContentBundle\Entity\Comment;
  7. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  8. use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
  9. class CommentListener implements EventSubscriberInterface
  10. {
  11.     /**
  12.      * @var TokenStorageInterface
  13.      */
  14.     protected $tokenStorage;
  15.     public function __construct(TokenStorageInterface $tokenStorage)
  16.     {
  17.         $this->tokenStorage $tokenStorage;
  18.     }
  19.     public function onSave(EntityEvent $event): void
  20.     {
  21.         $comment $event->getEntity();
  22.         if ($comment instanceof Comment) {
  23.             $user $this->tokenStorage->getToken()->getUser();
  24.             if ($user instanceof User && !$comment->getDescription()) {
  25.                 $comment->setAuthor($user);
  26.             } elseif (\is_string($user) && !$comment->getDescription()) {
  27.                 $comment->setDescription($user);
  28.             }
  29.         }
  30.     }
  31.     public static function getSubscribedEvents()
  32.     {
  33.         return [
  34.             'comment.pre_create' => 'onSave',
  35.             'comment.pre_update' => 'onSave',
  36.         ];
  37.     }
  38. }