<?php
namespace SettingsBundle\Security;
use AppBundle\Entity\User;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Core\Authorization\Voter\Voter;
/**
* ModuleVoter votes based on active module
*/
class ModuleVoter extends Voter
{
/**
* {@inheritdoc}
*/
protected function supports($attribute, $subject): bool
{
return $subject === null && 0 === strpos($attribute, 'MODULE_');
}
/**
* {@inheritdoc}
*/
protected function voteOnAttribute($attribute, $subject, TokenInterface $token): bool
{
$user = $token->getUser();
if (!$user instanceof User) {
return false;
}
$pattern = '/^(?P<module>MODULE_(?:(?:(?!_ROLE_).)*))(?:_ROLE_.*)?$/';
if (!preg_match($pattern, $attribute, $matches)) {
return false;
}
$module = $matches['module'];
if (!$user->hasRole($module)) {
return false;
}
if ($attribute === $module) {
return true;
}
return $user->hasRole($attribute);
}
}