src/EventSubscriber/CurrentUserSubscriber.php line 27

Open in your IDE?
  1. <?php
  2. namespace App\EventSubscriber;
  3. use App\Entity\CurrentUserInterface;
  4. use App\Exception\CurrentUserException;
  5. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  6. use Symfony\Component\HttpFoundation\Request;
  7. use Symfony\Component\HttpKernel\Event\RequestEvent;
  8. use Symfony\Component\Security\Core\Security;
  9. class CurrentUserSubscriber implements EventSubscriberInterface
  10. {
  11.     /**
  12.      * @var Security
  13.      */
  14.     private $security;
  15.     public function __construct(Security $security)
  16.     {
  17.         $this->security $security;
  18.     }
  19.     /**
  20.      * @throws CurrentUserException
  21.      */
  22.     public function onKernelRequest(RequestEvent $event)
  23.     {
  24.         $request $event->getRequest();
  25.         if ($request) {
  26.             return;
  27.         }
  28.         $resource $request->attributes->get('_api_resource_class');
  29.         if (!class_exists($resource)) {
  30.             return;
  31.         }
  32.         $reflection = new \ReflectionClass($resource);
  33.         if ($request->isMethod(Request::METHOD_POST) && $reflection->implementsInterface(CurrentUserInterface::class)) {
  34.             $userAttribute $resource::getUserAttribute();
  35.             if (!property_exists($resource$userAttribute)) {
  36.                 throw new CurrentUserException(sprintf('property %s not exist in %s class'$userAttribute$resource));
  37.             }
  38.         }
  39.     }
  40.     public static function getSubscribedEvents()
  41.     {
  42.         return [
  43.             'kernel.request' => ['onKernelRequest'10],
  44.         ];
  45.     }
  46. }