src/Security/Blo/ShopVoter.php line 12

Open in your IDE?
  1. <?php
  2. declare(strict_types=1);
  3. namespace App\Security\Blo;
  4. use App\Entity\Blo\Shop;
  5. use App\Entity\User;
  6. use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
  7. use Symfony\Component\Security\Core\Authorization\Voter\Voter;
  8. class ShopVoter extends Voter
  9. {
  10.     public const VIEW 'blo_shop_view';
  11.     public const EDIT 'blo_shop_edit';
  12.     public const MANAGE 'blo_shop_manage';
  13.     protected function supports(string $attributemixed $subject): bool
  14.     {
  15.         return $subject instanceof Shop
  16.             && \in_array($attribute, [self::VIEWself::EDITself::MANAGE], true);
  17.     }
  18.     protected function voteOnAttribute(string $attributemixed $subjectTokenInterface $token): bool
  19.     {
  20.         $user $token->getUser();
  21.         if (!$user instanceof User) {
  22.             return $attribute === self::VIEW;
  23.         }
  24.         /** @var Shop $shop */
  25.         $shop $subject;
  26.         return match ($attribute) {
  27.             self::VIEW => true,
  28.             self::EDIT => $this->canEdit($shop$user),
  29.             self::MANAGE => $this->canManage($shop$user),
  30.             default => false,
  31.         };
  32.     }
  33.     private function canEdit(Shop $shopUser $user): bool
  34.     {
  35.         if (\in_array('ROLE_ADMIN'$user->getRoles(), true)) {
  36.             return true;
  37.         }
  38.         return $shop->getOwner() === $user;
  39.     }
  40.     private function canManage(Shop $shopUser $user): bool
  41.     {
  42.         return $this->canEdit($shop$user);
  43.     }
  44. }