<?php
namespace App\Security\Voter;
use App\Entity\Lesson;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Core\Authorization\Voter\Voter;
use Symfony\Component\Security\Core\User\UserInterface;
class LessonVoter 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::EDIT,self::VIEW])
&& $subject instanceof Lesson;
}
/**
* @param string $attribute
* @param Lesson $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;
}
// ... (check conditions and return true to grant permission) ...
return match ($attribute) {
self::EDIT => $this->canEdit($user, $subject),
self::VIEW => $this->canView($user, $subject),
default => false,
};
}
private function canEdit(
UserInterface $user,
Lesson $subject
) {
return $user->getUserIdentifier() === $subject->getCoach()->getProfile()->getUser()->getUserIdentifier()
|| $user->getUserIdentifier() === $subject->getAuthor()->getUserIdentifier();
}
private function canView(
UserInterface $user,
Lesson $subject
) {
$otherUser = array_filter($subject->getAdditionalClient(), function ($client) use ($user) {
return $user->getUserIdentifier() === $client->getProfile()->getUser()->getUserIdentifier();
});
return $this->canEdit($user, $subject) || !empty($otherUser);
}
}