src/Security/Voter/Almacen/ModeloVoter.php line 12

Open in your IDE?
  1. <?php
  2. namespace App\Security\Voter\Almacen;
  3. use App\Entity\Ajustes\Usuario;
  4. use App\Entity\Almacen\Modelo;
  5. use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
  6. use Symfony\Component\Security\Core\Authorization\Voter\Voter;
  7. use Symfony\Component\Security\Core\Security;
  8. use Symfony\Component\Security\Core\User\UserInterface;
  9. class ModeloVoter extends Voter
  10. {
  11.     const VIEW      'MOD_VIEW';
  12.     const EDIT      'MOD_EDIT';
  13.     const DELETE    'MOD_DELETE';
  14.     private $security;
  15.     public function __construct(Security $security)
  16.     {
  17.         $this->security $security;
  18.     }
  19.     protected function supports(string $attribute$subject): bool
  20.     {
  21.         // replace with your own logic
  22.         // https://symfony.com/doc/current/security/voters.html
  23.         return in_array($attribute, [self::EDITself::VIEWself::DELETE])
  24.             && $subject instanceof Modelo;
  25.     }
  26.     protected function voteOnAttribute(string $attribute$subjectTokenInterface $token): bool
  27.     {
  28.         $user $token->getUser();
  29.         // if the user is anonymous, do not grant access
  30.         if (!$user instanceof UserInterface) {
  31.             return false;
  32.         }
  33.         switch ($attribute) {
  34.             case self::EDIT:
  35.                 // logic to determine if the user can EDIT
  36.                 // return true or false
  37.                 return $this->canEdit($subject$user);
  38.             case self::VIEW:
  39.                 // logic to determine if the user can VIEW
  40.                 // return true or false
  41.                 return $this->canView($subject$user);
  42.             case self::DELETE:
  43.                 // logic to determine if the user can DELETE
  44.                 // return true or false
  45.                 return $this->canDelete($subject$user);
  46.         }
  47.         return false;
  48.     }
  49.     private function canView(Modelo $subject,Usuario $user){
  50.         if ($this->security->isGranted('ROLE_MOD_VIEW'))
  51.             return true;
  52.         
  53.         
  54.         return false;
  55.     }
  56.     private function canEdit(Modelo $subject,Usuario $user){
  57.         if ($this->security->isGranted('ROLE_MOD_EDIT'))
  58.             return true;
  59.         
  60.         return false;
  61.     }
  62.     private function canDelete(Modelo $subject,Usuario $user){
  63.         if ($this->security->isGranted('ROLE_MOD_DELETE'))
  64.             return true;
  65.         return false;
  66.     }
  67. }