<?php
namespace App\Security\Voter\Api;
use App\Entity\Room;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Core\Authorization\Voter\Voter;
use Symfony\Component\Security\Core\User\UserInterface;
class RoomVoter extends Voter
{
public const VIEW = 'view';
public const NEW = 'new';
public function __construct(
private EntityManagerInterface $entityManager
)
{
}
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::VIEW
])
&& $subject instanceof \App\Entity\Room;
}
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(
$subject, $user
)
{
return true;
}
/**
* @param $subject Room
* @param $user
* @return bool
*/
private function canView($subject, $user){
return $subject->getCoach()->getUserIdentifier() === $user->getUserIdentifier() || $subject->getClient()->getUserIdentifier() === $user->getUserIdentifier();
}
}