<?php
namespace App\Security\Voter\User;
use App\Entity\Account;
use App\Security\ApiUser;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Core\Authorization\Voter\Voter;
class AmateurUpgradeVoter extends Voter
{
public const PERMISSION_UPGRADE = 'upgrade';
protected function supports(string $attribute, $subject): bool
{
if (!$subject instanceof Account) {
return false;
}
return in_array($attribute, [self::PERMISSION_UPGRADE], true);
}
protected function voteOnAttribute(string $attribute, $subject, TokenInterface $token): bool
{
$user = $token->getUser();
if (!$user instanceof ApiUser) {
return false;
}
/*
* @var $subject Account
*/
if (self::PERMISSION_UPGRADE == $attribute) {
return $this->canUpgrade($subject, $user);
}
return false;
}
protected function canUpgrade(Account $subject, ApiUser $user): bool
{
// admin should be able to upgrade anyone
if ($user->getIsAdmin()) {
return true;
}
// active user is already an amateur, so no longer possible
if ($user->getIsAmateur()) {
return false;
}
return $user->getAccount()->getId() === $subject->getId();
}
}