src/Security/Voter/Configuracion/MaterialVoter.php line 12

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