src/Security/Voter/CategoryVoter.php line 13

Open in your IDE?
  1. <?php
  2. namespace App\Security\Voter;
  3. use App\Entity\Category;
  4. use App\User\Entity\User;
  5. use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
  6. use Symfony\Component\Security\Core\Authorization\Voter\Voter;
  7. /**
  8.  * Security voter to control access to Category entities based on client ownership.
  9.  */
  10. class CategoryVoter extends Voter
  11. {
  12.     public const VIEW 'view';
  13.     public const EDIT 'edit';
  14.     public const DELETE 'delete';
  15.     protected function supports(string $attribute$subject): bool
  16.     {
  17.         return in_array($attribute, [self::VIEWself::EDITself::DELETE], true)
  18.             && $subject instanceof Category;
  19.     }
  20.     protected function voteOnAttribute(string $attribute$subjectTokenInterface $token): bool
  21.     {
  22.         $user $token->getUser();
  23.         if (!$user instanceof User) {
  24.             return false;
  25.         }
  26.         if (in_array('ROLE_SUPER_USER'$user->getRoles(), true)) {
  27.             return true;
  28.         }
  29.         /** @var Category $category */
  30.         $category $subject;
  31.         $userClient $user->getClient();
  32.         if (!$userClient) {
  33.             return false;
  34.         }
  35.         $categoryClient $category->getClient();
  36.         if (!$categoryClient) {
  37.             return false;
  38.         }
  39.         if ($userClient->getId() !== $categoryClient->getId()) {
  40.             return false;
  41.         }
  42.         return in_array('ROLE_MANAGER'$user->getRoles(), true)
  43.             || in_array('ROLE_ADMIN'$user->getRoles(), true);
  44.     }
  45. }