<?php
namespace App\Security\Voter\PartnerApi;
use App\Entity\Channel\Channel;
use App\Entity\PartnerApi\PartnerApiUser;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Core\Authorization\Voter\Voter;
class ChannelVoter extends Voter
{
public const EDIT = 'CHANNEL_EDIT';
public const VIEW = 'CHANNEL_VIEW';
protected function supports(string $attribute, $subject): bool
{
return in_array($attribute, [self::EDIT, self::VIEW])
&& $subject instanceof Channel;
}
protected function voteOnAttribute(string $attribute, $subject, TokenInterface $token): bool
{
$user = $token->getUser();
// if the user is anonymous, do not grant access
if (!$user instanceof PartnerApiUser) {
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(PartnerApiUser $user, Channel $channel): bool
{
return $this->canView($user, $channel);
}
private function canView(PartnerApiUser $user, Channel $channel): bool
{
return $user->getChannels()->contains($channel);
}
}