<?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;
use Symfony\Component\Security\Core\User\UserInterface;
/**
* Class UserVoter.
*/
class UserVoter extends Voter
{
// Permissions.
const ACCOUNT_VIEW = 'account_view';
// Full list.
const PERMISSIONS = [
self::ACCOUNT_VIEW,
];
/**
* {@inheritdoc}
*/
protected function supports($attribute, $subject): bool
{
return in_array($attribute, self::PERMISSIONS) && ($subject instanceof User);
}
/**
* {@inheritdoc}
*/
protected function voteOnAttribute($attribute, $subject, TokenInterface $token): bool
{
/** @var User $user */
$user = $token->getUser();
// If the user is anonymous, do not grant access.
if (!$user instanceof UserInterface) {
return false;
}
// Check conditions and provide access bases on it.
switch ($attribute) {
case self::ACCOUNT_VIEW:
return $this->canView($subject, $user);
default:
break;
}
return false;
}
/**
* Check that current user can view account space.
*/
public function canView(User $subject, User $user): bool
{
return $subject->getId() === $user->getId();
}
}