<?php
namespace App\Security\Voter;
use App\Entity\BootCampReservation;
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 BootCampReservationVoter extends Voter
{
public const EDIT = "edit";
public const VIEW = "view";
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::VIEW, self::EDIT])
&& $subject instanceof \App\Entity\BootCampReservation;
}
/**
* @param string $attribute
* @param BootCampReservation $subject
* @param TokenInterface $token
* @return bool
*/
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::EDIT => $this->canEdit($user, $subject),
"default" => false
};
}
private function canEdit(
UserInterface $user,
BootCampReservation $subject
): bool {
return match(true){
in_array("ROLE_COACH", $user->getRoles()) => $user->getUserIdentifier() === $subject->getBootcamp()->getCoach()->getProfile()->getUser(),
default => $user->getUserIdentifier() === $subject->getClient()->getProfile()->getUser()->getUserIdentifier()
};
}
}