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 Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
  5. use Symfony\Component\Security\Core\Authorization\Voter\Voter;
  6. use Symfony\Component\Security\Core\User\UserInterface;
  7. class CompanyVoter extends Voter
  8. {
  9.     protected function supports(string $attribute$subject): bool
  10.     {
  11.         // replace with your own logic
  12.         // https://symfony.com/doc/current/security/voters.html
  13.         return in_array($attribute, ['COMPANY_UPLOAD''COMPANY_UPDATE'], true) && $subject instanceof Company;
  14.     }
  15.     protected function voteOnAttribute(string $attribute$subjectTokenInterface $token): bool
  16.     {
  17.         $user $token->getUser();
  18.         // if the user is anonymous, do not grant access
  19.         if (!$user instanceof UserInterface) {
  20.             return false;
  21.         }
  22.         /** @var Company $company */
  23.         $company $subject;
  24.         // ... (check conditions and return true to grant permission) ...
  25.         switch ($attribute) {
  26.             case 'COMPANY_UPLOAD':
  27.                 // logic to determine if the user can EDIT
  28.                 // return true or false
  29.                 return ($company->getUser() === $user)
  30.                     || in_array('ROLE_ADMIN'$user->getRoles(), true);
  31.             case 'COMPANY_UPDATE':
  32.                 // logic to determine if the user can VIEW
  33.                 // return true or false
  34.                 return $company->getUser() === $user;
  35.         }
  36.         return false;
  37.     }
  38. }