<?php
namespace App\Security\Voter\PartnerApi;
use App\Entity\Channel\Channel;
use App\Entity\Exercise\Exercise;
use App\Entity\PartnerApi\PartnerApiUser;
use App\Entity\Scholar\Chapter\Chapter;
use App\Entity\Scholar\PracticalCase\PracticalCase;
use App\Entity\Scholar\ScholarInterface;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Core\Authorization\Voter\Voter;
class ScholarVoter extends Voter
{
public const LIST = 'SCHOLAR_LIST';
public const CREATE = 'SCHOLAR_CREATE';
public const EDIT = 'SCHOLAR_EDIT';
public const VIEW = 'SCHOLAR_VIEW';
protected function supports(string $attribute, $subject): bool
{
return match ($attribute) {
self::LIST, self::CREATE => $subject instanceof Channel,
self::EDIT, self::VIEW =>
$subject instanceof ScholarInterface
|| $subject instanceof Chapter
|| $subject instanceof PracticalCase
|| $subject instanceof Exercise,
default => false,
};
}
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::LIST => $this->canList($user, $subject),
self::CREATE => $this->canCreate($user, $subject),
self::EDIT => $this->canEdit($user, $subject),
self::VIEW => $this->canView($user, $subject),
default => false,
};
}
private function canList(PartnerApiUser $user, Channel $channel): bool
{
return $user->getChannels()->contains($channel);
}
private function canCreate(PartnerApiUser $user, Channel $channel): bool
{
return $this->canList($user, $channel);
}
private function canEdit(PartnerApiUser $user, ScholarInterface|Chapter|PracticalCase|Exercise $scholarObject): bool
{
$createdBy = null;
if (method_exists($scholarObject, 'getCreatedBy')) {
$createdBy = $scholarObject->getCreatedBy();
} elseif (method_exists($scholarObject, 'getLesson')) {
$createdBy = $scholarObject->getLesson()->getCreatedBy();
}
return $this->canView($user, $scholarObject)
&& $createdBy === $user->getUser();
}
private function canView(PartnerApiUser $user, ScholarInterface|Chapter|PracticalCase|Exercise $scholarObject): bool
{
$channel = null;
if (method_exists($scholarObject, 'getOwnerChannel')) {
$channel = $scholarObject->getOwnerChannel();
} elseif (method_exists($scholarObject, 'getLesson')) {
$channel = $scholarObject->getLesson()->getOwnerChannel();
}
return $this->canList($user, $channel);
}
}