<?php
declare(strict_types=1);
namespace App\Security\Voter;
use App\Entity\Event;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Core\Authorization\Voter\Voter;
use Symfony\Component\Security\Core\User\UserInterface;
use Symfony\Component\Security\Core\Security;
class EventVoter extends Voter
{
public function __construct(private readonly Security $security)
{
}
protected function supports($attribute, $subject): bool
{
// only vote on `Event` objects
if (!$subject instanceof Event) {
return false;
}
// if the attribute isn't one we support, return false
return in_array($attribute, ['edit', 'delete']);
}
protected function voteOnAttribute($attribute, $subject, TokenInterface $token): bool
{
/**@var Event $event */
$event = $subject;
$user = $token->getUser();
// if the user is anonymous, do not grant access
if (!$user instanceof UserInterface) {
return false;
}
// ROLE_CHIEF can do anything! The power!
if ($this->security->isGranted('ROLE_CHIEF')) {
return true;
}
return match ($attribute) {
// Users may edit THEIR events
'edit' => $user === $event->getAssignedTo(),
// Users may delete THEIR events
'delete' => $user === $event->getAssignedTo(),
default => false,
};
}
}