src/App/Security/ListingOwnerVoter.php line 11

Open in your IDE?
  1. <?php
  2. namespace App\Security;
  3. use Aqarmap\Bundle\ListingBundle\Entity\Listing;
  4. use Aqarmap\Bundle\UserBundle\Entity\User;
  5. use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
  6. use Symfony\Component\Security\Core\Authorization\AuthorizationCheckerInterface;
  7. use Symfony\Component\Security\Core\Authorization\Voter\Voter;
  8. class ListingOwnerVoter extends Voter
  9. {
  10.     const OWNER 'LISTING_OWNER';
  11.     private AuthorizationCheckerInterface $authorizationChecker;
  12.     public function __construct(AuthorizationCheckerInterface $authorizationChecker)
  13.     {
  14.         $this->authorizationChecker $authorizationChecker;
  15.     }
  16.     protected function supports(string $attribute$subject): bool
  17.     {
  18.         return $attribute === self::OWNER && $subject instanceof Listing;
  19.     }
  20.     protected function voteOnAttribute(string $attribute$subjectTokenInterface $token): bool
  21.     {
  22.         if ($this->authorizationChecker->isGranted('ROLE_ADMIN')) {
  23.             return true;
  24.         }
  25.         $user $token->getUser();
  26.         if (!$user instanceof User) {
  27.             return false;
  28.         }
  29.         /** @var Listing $listing */
  30.         $listing $subject;
  31.         return $user->getId() === $listing->getUser()->getId();
  32.     }
  33. }