src/Events/CommunityPostReadSubscriber.php line 30

Open in your IDE?
  1. <?php
  2. namespace App\Events;
  3. use ApiPlatform\Core\Bridge\Doctrine\Orm\Paginator;
  4. use Symfony\Component\Security\Core\Security;
  5. use Symfony\Component\HttpKernel\KernelEvents;
  6. use Symfony\Component\HttpKernel\Event\ViewEvent;
  7. use ApiPlatform\Core\EventListener\EventPriorities;
  8. use App\Entity\CommunityConsultation;
  9. use App\Entity\CommunityPost;
  10. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  11. class CommunityPostReadSubscriber implements EventSubscriberInterface
  12. {
  13.     /**
  14.      * @var Security
  15.      */
  16.     private $security;
  17.     public function __construct(Security $security)
  18.     {
  19.         $this->security $security;
  20.     }
  21.     /**
  22.      * @param ViewEvent $event
  23.      * @return void
  24.      */
  25.     public function setUserVote(ViewEvent $event)
  26.     {
  27.         $object $event->getControllerResult();
  28.         if ($object instanceof CommunityPost or $object instanceof CommunityConsultation) {
  29.             $object->voteUser($this->security->getUser());
  30.         }
  31.         if ($object instanceof Paginator && count($object) > 0) {
  32.             foreach ($object as $objet) {
  33.                 if (!($objet instanceof CommunityPost or $objet instanceof CommunityConsultation)) {
  34.                     return;
  35.                 }
  36.                 $objet->voteUser($this->security->getUser());
  37.             }
  38.         }
  39.     }
  40.     /**
  41.      * @return array<string, mixed>
  42.      */
  43.     public static function getSubscribedEvents(): array
  44.     {
  45.         return [
  46.             KernelEvents::VIEW => [ 'setUserVote'EventPriorities::PRE_SERIALIZE ]
  47.         ];
  48.     }
  49. }