<?php
namespace App\Security\Voter;
use App\Entity\User;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Core\Authorization\Voter\Voter;
class ClientPermissionVoter extends Voter
{
const ATTR = 'clientPermission';
protected function supports(string $attribute, $subject): bool
{
// if the attribute isn't one we support, return false
if ($attribute !== self::ATTR) {
return false;
}
// only vote on `Invoice` objects
if (!is_string($subject)) {
return false;
}
return true;
}
protected function voteOnAttribute(string $attribute, $subject, TokenInterface $token): bool
{
$loggedUser = $token->getUser();
if (!$loggedUser instanceof User) {
// the user must be logged in; if not, deny access
return false;
}
/** @var string $permissionName */
$permissionName = $subject;
foreach ($loggedUser->getClient()->getPermissions() as $permission) {
if ($permission->getName() === $permissionName) {
return true;
}
}
return false;
}
}