<?php 
 
declare(strict_types=1); 
 
namespace Hitso\Bundle\ContentBundle\EventListener; 
 
use Hitso\Bundle\CommonBundle\Doctrine\Event\EntityEvent; 
use Hitso\Bundle\CommonBundle\Entity\User; 
use Hitso\Bundle\ContentBundle\Entity\Comment; 
use Symfony\Component\EventDispatcher\EventSubscriberInterface; 
use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface; 
 
class CommentListener implements EventSubscriberInterface 
{ 
    /** 
     * @var TokenStorageInterface 
     */ 
    protected $tokenStorage; 
 
    public function __construct(TokenStorageInterface $tokenStorage) 
    { 
        $this->tokenStorage = $tokenStorage; 
    } 
 
    public function onSave(EntityEvent $event): void 
    { 
        $comment = $event->getEntity(); 
        if ($comment instanceof Comment) { 
            $user = $this->tokenStorage->getToken()->getUser(); 
 
            if ($user instanceof User && !$comment->getDescription()) { 
                $comment->setAuthor($user); 
            } elseif (\is_string($user) && !$comment->getDescription()) { 
                $comment->setDescription($user); 
            } 
        } 
    } 
 
    public static function getSubscribedEvents() 
    { 
        return [ 
            'comment.pre_create' => 'onSave', 
            'comment.pre_update' => 'onSave', 
        ]; 
    } 
}