src/EventSubscriber/User/UserWatchListSubscriber.php line 32

Open in your IDE?
  1. <?php
  2. namespace App\EventSubscriber\User;
  3. use ApiPlatform\Core\EventListener\EventPriorities;
  4. use App\Entity\User\StudentWatchList;
  5. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  6. use Symfony\Component\HttpFoundation\Request;
  7. use Symfony\Component\HttpKernel\Event\ViewEvent;
  8. use Symfony\Component\HttpKernel\KernelEvents;
  9. use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
  10. final class UserWatchListSubscriber implements EventSubscriberInterface
  11. {
  12.     /**
  13.      * @var TokenStorageInterface
  14.      */
  15.     private $tokenStorage;
  16.     public function __construct(TokenStorageInterface $tokenStorage)
  17.     {
  18.         $this->tokenStorage $tokenStorage;
  19.     }
  20.     public static function getSubscribedEvents()
  21.     {
  22.         return [
  23.             KernelEvents::VIEW => ['attachOwner'EventPriorities::PRE_WRITE],
  24.         ];
  25.     }
  26.     public function attachOwner(ViewEvent $event)
  27.     {
  28.         $watchlist $event->getControllerResult();
  29.         $method $event->getRequest()->getMethod();
  30.         if (!$watchlist instanceof StudentWatchList || Request::METHOD_POST !== $method) {
  31.             // Only handle Article entities (Event is called on any Api entity)
  32.             return;
  33.         }
  34. //        // maybe these extra null checks are not even needed
  35.         $token $this->tokenStorage->getToken();
  36.         if (!$token) {
  37.             return;
  38.         }
  39.         $owner $token->getUser();
  40.         if (!$owner instanceof User) {
  41.             return;
  42.         }
  43.         // Attach the user to the not yet persisted Article
  44.         $watchlist->setUser($owner);
  45.         $event->setControllerResult($watchlist);
  46.     }
  47. }