<?php
namespace App\Events;
use ApiPlatform\Core\Bridge\Doctrine\Orm\Paginator;
use Symfony\Component\Security\Core\Security;
use Symfony\Component\HttpKernel\KernelEvents;
use Symfony\Component\HttpKernel\Event\ViewEvent;
use ApiPlatform\Core\EventListener\EventPriorities;
use App\Entity\CommunityConsultation;
use App\Entity\CommunityPost;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
class CommunityPostReadSubscriber implements EventSubscriberInterface
{
/**
* @var Security
*/
private $security;
public function __construct(Security $security)
{
$this->security = $security;
}
/**
* @param ViewEvent $event
* @return void
*/
public function setUserVote(ViewEvent $event)
{
$object = $event->getControllerResult();
if ($object instanceof CommunityPost or $object instanceof CommunityConsultation) {
$object->voteUser($this->security->getUser());
}
if ($object instanceof Paginator && count($object) > 0) {
foreach ($object as $objet) {
if (!($objet instanceof CommunityPost or $objet instanceof CommunityConsultation)) {
return;
}
$objet->voteUser($this->security->getUser());
}
}
}
/**
* @return array<string, mixed>
*/
public static function getSubscribedEvents(): array
{
return [
KernelEvents::VIEW => [ 'setUserVote', EventPriorities::PRE_SERIALIZE ]
];
}
}