<?php
namespace App\Security\Voter\Api;
use App\Entity\Profile\Profile;
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 ProfileVoter extends Voter
{
public const EDIT = 'edit';
public const NEW = 'new';
protected function supports(string $attribute, $subject): bool
{
return in_array($attribute, [self::EDIT, self::NEW])
&& $subject instanceof Profile;
}
protected function voteOnAttribute(string $attribute, $subject, TokenInterface $token): bool
{
$user = $token->getUser();
if (!$user instanceof UserInterface) {
return false;
}
return match ($attribute) {
self::EDIT, self::NEW => $this->canEdit($user, $subject),
default => false,
};
}
private function canEdit(User $user, Profile $profile): bool
{
return $profile->getUser() === $user;
}
}