<?php
namespace App\Security\Voter;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Core\Authorization\Voter\Voter;
use Symfony\Component\Security\Core\User\UserInterface;
class BootCampVoter extends Voter
{
public const NEW = 'new';
public const EDIT = 'edit';
protected function supports(string $attribute, $subject): bool
{
// replace with your own logic
// https://symfony.com/doc/current/security/voters.html
return in_array($attribute, [self::NEW, self::EDIT])
&& $subject instanceof \App\Entity\BootCamp;
}
protected function voteOnAttribute(string $attribute, $subject, TokenInterface $token): bool
{
$user = $token->getUser();
// if the user is anonymous, do not grant access
if (!$user instanceof UserInterface) {
return false;
}
return match ($attribute){
self::NEW => $this->canCreate($user),
self::EDIT => $this->canEdit($subject, $user),
default => false
};
}
private function canCreate(
UserInterface $user
): bool {
return in_array("ROLE_COACH", $user->getRoles());
}
private function canEdit(
mixed $subject,
UserInterface $user
): bool {
return $this->canCreate($user) && $subject->getCoach()->getProfile()->getUser()->getUserIdentifier() === $user->getUserIdentifier();
}
}