src/Security/Voter/CompanyVoter.php line 12

Open in your IDE?
  1. <?php
  2. namespace App\Security\Voter;
  3. use App\Entity\Company;
  4. use App\Entity\User;
  5. use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
  6. use Symfony\Component\Security\Core\Authorization\Voter\Voter;
  7. use Symfony\Component\Security\Core\User\UserInterface;
  8. use Symfony\Component\Security\Core\Security;
  9. class CompanyVoter extends Voter
  10. {
  11.     const VIEW ="ver";
  12.     const EDIT ="editar";
  13.     const DELETE "eliminar";
  14.     private $security;
  15.     public function __construct(Security $security)
  16.     {
  17.         $this->security $security;
  18.     }
  19.     protected function supports($attribute$subject)
  20.     {
  21.         // if the attribute isn't one we support, return false
  22.         if (!in_array($attribute, [self::VIEWself::EDIT])) {
  23.             return false;
  24.         }
  25.         // only vote on `Company` objects
  26.         if (!$subject instanceof Company) {
  27.             return false;
  28.         }
  29.         return true;
  30.     }
  31.     protected function voteOnAttribute($attribute$subjectTokenInterface $token)
  32.     {
  33.         $user $token->getUser();
  34.         // if the user is anonymous, do not grant access
  35.         if (!$user instanceof UserInterface) {
  36.             return false;
  37.         }
  38.         // ROLE_ADMIN can do anything! The power!
  39.         if ($this->security->isGranted('ROLE_ADMIN')) {
  40.             return true;
  41.         }
  42.         // ... (check conditions and return true to grant permission) ...
  43.         switch ($attribute) {
  44.             case self::VIEW:
  45.                 return $this->canView($subject$user);
  46.             case self::EDIT:
  47.                 return $this->canEdit($subject$user);
  48.             case self::DELETE:
  49.                 return $this->canDelete($subject$user);
  50.             break;
  51.         }
  52.         return false;        
  53.     }
  54.     private function canView(Company $companyUser $user)
  55.     {        
  56.         return $user === $company->getUser();
  57.     }
  58.     private function canEdit(Company $companyUser $user)
  59.     {
  60.         return $user === $company->getUser();
  61.     }
  62.     private function canDelete(Company $companyUser $user)
  63.     {
  64.         return $user === $company->getUser();
  65.     }
  66. }