<?php
declare(strict_types=1);
namespace App\Core\Security\Voters;
use App\Entity\User;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Core\Authorization\Voter\Voter;
class ApiVoter extends Voter
{
/**
* Determines if the attribute and subject are supported by this voter.
*
* @param string $attribute An attribute
* @param mixed $subject The subject to secure, e.g. an object the user wants to access or any other PHP type
*
* @return bool True if the attribute and subject are supported, false otherwise
*/
protected function supports($attribute, $subject)
{
if (!\in_array($attribute, [User::ROLE_API_READ, User::ROLE_API_WRITE], true)) {
return false;
}
return true;
}
/**
* Perform a single access check operation on a given attribute, subject and token.
* It is safe to assume that $attribute and $subject already passed the "supports()" method check.
*
* @param string $attribute
* @param mixed $subject
* @param TokenInterface $token
*
* @return bool
*/
protected function voteOnAttribute($attribute, $subject, TokenInterface $token)
{
$user = $token->getUser();
if (!$user instanceof User) {
return false;
}
switch ($attribute) {
case User::ROLE_API_READ:
return $this->canRead($user);
case User::ROLE_API_WRITE:
return $this->canWrite($user);
}
throw new \LogicException('This code should not be reached!');
}
private function canRead(User $user): bool
{
return \in_array(User::ROLE_API_WRITE, $user->getRoles(), true) ||
\in_array(User::ROLE_API_READ, $user->getRoles(), true);
}
private function canWrite(User $user): bool
{
return \in_array(User::ROLE_API_WRITE, $user->getRoles(), true);
}
}