<?php
namespace App\Security\Voter\Api;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Core\Authorization\Voter\Voter;
use Symfony\Component\Security\Core\User\UserInterface;
use function dd;
class RoomMessageVoter extends Voter
{
public const VIEW = 'view';
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::VIEW,
self::NEW,
self::EDIT
])
&& $subject instanceof \App\Entity\RoomMessage;
}
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::NEW => $this->canCreate($subject, $user),
self::VIEW => $this->canView($subject, $user),
default => false,
};
}
private function canCreate(
mixed $subject,
UserInterface $user
): bool {
return
$subject->getAuthor()->getUserIdentifier() === $user->getUserIdentifier()
&& $this->canView($subject, $user);
}
private function canView(
mixed $subject,
UserInterface $user
): bool {
return $subject->getRoom()->getCoach()->getUserIdentifier() === $user->getUserIdentifier()
|| $subject->getRoom()->getClient()->getUserIdentifier() === $user->getUserIdentifier();
}
}