<?php
namespace App\Security\Voter;
use App\Entity\Category;
use App\User\Entity\User;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Core\Authorization\Voter\Voter;
/**
* Security voter to control access to Category entities based on client ownership.
*/
class CategoryVoter extends Voter
{
public const VIEW = 'view';
public const EDIT = 'edit';
public const DELETE = 'delete';
protected function supports(string $attribute, $subject): bool
{
return in_array($attribute, [self::VIEW, self::EDIT, self::DELETE], true)
&& $subject instanceof Category;
}
protected function voteOnAttribute(string $attribute, $subject, TokenInterface $token): bool
{
$user = $token->getUser();
if (!$user instanceof User) {
return false;
}
if (in_array('ROLE_SUPER_USER', $user->getRoles(), true)) {
return true;
}
/** @var Category $category */
$category = $subject;
$userClient = $user->getClient();
if (!$userClient) {
return false;
}
$categoryClient = $category->getClient();
if (!$categoryClient) {
return false;
}
if ($userClient->getId() !== $categoryClient->getId()) {
return false;
}
return in_array('ROLE_MANAGER', $user->getRoles(), true)
|| in_array('ROLE_ADMIN', $user->getRoles(), true);
}
}