<?php
namespace App\Security\Voter;
use App\Entity\Testimony;
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 TestimonyVoter extends Voter
{
public const EDIT = 'POST_EDIT';
public const VIEW = 'POST_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::EDIT, self::VIEW])
&& $subject instanceof \App\Entity\Testimony;
}
/**
* @param string $attribute
* @param Testimony $subject
* @param TokenInterface $token
* @return bool
*/
protected function voteOnAttribute(string $attribute, $subject, TokenInterface $token): bool
{
/** @var User $user */
$user = $token->getUser();
// if the user is anonymous, do not grant access
if (!$user instanceof UserInterface && !in_array("ROLE_COACH", $user->getRoles())) {
return false;
}
return match($attribute){
self::EDIT => $user->getProfile()->getCoach()->getUuid() == $subject->getCoach()->getUuid(),
default => false,
};
}
}