<?php
namespace App\Security\Core;
use App\Services\Admin\EasyAdminService;
use App\Entity\Core\Quiz\Quiz;
use Symfony\Component\HttpFoundation\RequestStack;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Core\Authorization\Voter\Voter;
use Symfony\Component\Security\Core\Security;
class QuizVoter extends Voter
{
const PERMISSION = 'quizEntityPermission';
const INDEX_ACTION = 'quizIndexAction';
const NEW_ACTION = 'quizNewAction';
const EDIT_ACTION = 'quizEditAction';
const DELETE_ACTION = 'quizDeleteAction';
private Security $security;
private EasyAdminService $easyAdminService;
private RequestStack $requestStack;
public function __construct(Security $security, EasyAdminService $easyAdminService, RequestStack $requestStack)
{
$this->security = $security;
$this->easyAdminService = $easyAdminService;
$this->requestStack = $requestStack;
}
protected function supports(string $attribute, $subject): bool
{
// For index and new, $subject will always be null. For permission, it will be null when trying to create a new entity.
if (in_array($attribute, [self::INDEX_ACTION, self::NEW_ACTION, self::PERMISSION])) {
return true;
}
if (in_array($attribute, [self::EDIT_ACTION, self::DELETE_ACTION])) {
return $subject instanceof Quiz;
}
return false;
}
protected function voteOnAttribute(string $attribute, $subject, TokenInterface $token): bool
{
if ($attribute === self::INDEX_ACTION) {
// Allow everyone to list - the entity permissions will still apply and hide entities you are not allowed
// to access.
return true;
}
if ($attribute === self::NEW_ACTION || $attribute === self::PERMISSION && $subject === null) {
// Anyone with cms access should be able to create new quizzes
return true;
}
if (!$subject instanceof Quiz) {
throw new \LogicException("Invalid type for voter and attribute.");
}
return $this->checkEntityPermissions($subject);
}
public function checkEntityPermissions(Quiz $subject): bool
{
// ROLE_SUPER_ADMIN inherits ROLE_ADMIN, and will also be included here.
if ($this->security->isGranted('ROLE_ADMIN')) {
return true;
}
$publication = $subject->getPublication();
if ($publication === null) {
try {
// When creating a new quiz in QuizFromPublicationCrudController
$publication = $this->easyAdminService->getPublication($this->requestStack->getCurrentRequest());
} catch (\Exception) {}
}
if ($publication !== null) {
return $this->easyAdminService->userCanAccessPublication($publication);
}
return false;
}
}