src/Security/Voter/CompanyVoter.php line 10

Open in your IDE?
  1. <?php
  2. namespace App\Security\Voter;
  3. use App\Entity\Company;
  4. use App\Service\VoterSecurityService;
  5. use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
  6. use Symfony\Component\Security\Core\Authorization\Voter\Voter;
  7. class CompanyVoter extends Voter
  8. {
  9.     public const EDIT 'EDIT'// infos and employee
  10.     public const VIEW 'VIEW';
  11.     public const VIEW_PREMIUM 'VIEW_PREMIUM';
  12.     public const VIEW_CHILDREN 'VIEW_CHILDREN';
  13.     public const ADD_CHILDREN 'ADD_CHILDREN'// add company child
  14.     public function __construct(private readonly VoterSecurityService $voterSecurityService)
  15.     {
  16.     }
  17.     protected function supports(string $attribute$subject): bool
  18.     {
  19.         return in_array($attribute, [
  20.             self::EDITself::VIEW,
  21.             self::VIEW_CHILDRENself::ADD_CHILDRENself::VIEW_PREMIUM,
  22.         ])
  23.             && $subject instanceof Company;
  24.     }
  25.     protected function voteOnAttribute(string $attribute$subjectTokenInterface $token): bool
  26.     {
  27.         $user $token->getUser();
  28.         if (!$this->voterSecurityService->isUserAllowed($user)) {
  29.             return false;
  30.         }
  31.         $this->voterSecurityService->isUserInElement($user$subject);
  32.         if (!$this->voterSecurityService->isUserInElement($user$subject)) {
  33.             return false;
  34.         }
  35.         return match ($attribute) {
  36.             self::VIEW => true,
  37.             self::VIEW_PREMIUM => $user->isPremium(),
  38.             self::EDIT => $this->voterSecurityService->allowedEditElement($subject),
  39.             self::VIEW_CHILDREN => $subject->isParent(), // check if is isParent === true in Company,
  40.             self::ADD_CHILDREN => $subject->isPremium() && $subject->isParent() &&
  41.                 $this->voterSecurityService->isUserManagerCompany(),
  42.             default => false,
  43.         };
  44.     }
  45. }