<?php
namespace App\Voter;
use App\Entity\Supplier;
use App\Entity\User as UserEntity;
use App\Model\User\User;
use Exception;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Core\Authorization\Voter\Voter;
class UserVoter extends Voter
{
public const SEARCH_USER = 'search_user';
private $user;
public function __construct(User $user)
{
$this->user = $user;
}
protected function supports($attribute, $subject): bool
{
// if the attribute isn't one we support, return false
if (! in_array($attribute, [
self::SEARCH_USER
])) {
return false;
}
return true;
}
/**
* @param string $attribute
* @param Supplier $entity
*
* @return bool
* @throws Exception
*/
protected function voteOnAttribute($attribute, $entity, TokenInterface $token): bool
{
$userEntity = $token->getUser();
if (! $userEntity instanceof UserEntity) {
// the user must be logged in; if not, deny access
return false;
}
$this->user->setEntity($userEntity);
switch ($attribute) {
case self::SEARCH_USER:
return $this->user->canSearchUser();
}
return false;
}
}