src/SettingsBundle/Security/ModuleVoter.php line 12

Open in your IDE?
  1. <?php
  2. namespace SettingsBundle\Security;
  3. use AppBundle\Entity\User;
  4. use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
  5. use Symfony\Component\Security\Core\Authorization\Voter\Voter;
  6. /**
  7.  * ModuleVoter votes based on active module
  8.  */
  9. class ModuleVoter extends Voter
  10. {
  11.     /**
  12.      * {@inheritdoc}
  13.      */
  14.     protected function supports($attribute$subject): bool
  15.     {
  16.         return $subject === null && === strpos($attribute'MODULE_');
  17.     }
  18.     /**
  19.      * {@inheritdoc}
  20.      */
  21.     protected function voteOnAttribute($attribute$subjectTokenInterface $token): bool
  22.     {
  23.         $user $token->getUser();
  24.         if (!$user instanceof User) {
  25.             return false;
  26.         }
  27.         $pattern '/^(?P<module>MODULE_(?:(?:(?!_ROLE_).)*))(?:_ROLE_.*)?$/';
  28.         if (!preg_match($pattern$attribute$matches)) {
  29.             return false;
  30.         }
  31.         $module $matches['module'];
  32.         if (!$user->hasRole($module)) {
  33.             return false;
  34.         }
  35.         if ($attribute === $module) {
  36.             return true;
  37.         }
  38.         return $user->hasRole($attribute);
  39.     }
  40. }