<?php
namespace CoreBundle\Security;
use CoreBundle\Entity\Publisher;
use CoreBundle\Entity\PublisherPermission;
use CoreBundle\Entity\PublisherPermissionRepository;
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\Security;
class PublisherVoter extends Voter
{
const PERMISSION = 'publisherEntityPermission';
const INDEX_ACTION = 'publisherIndexAction';
const NEW_ACTION = 'publisherNewAction';
const EDIT_ACTION = 'publisherEditAction';
const DELETE_ACTION = 'publisherDeleteAction';
private EntityManagerInterface $em;
private Security $security;
public function __construct(EntityManagerInterface $em, Security $security)
{
$this->em = $em;
$this->security = $security;
}
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 Publisher;
}
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) {
// Includes ROLE_SUPER_ADMIN by inheritance.
// Editors and authors should not be allowed to create new publishers.
return $this->security->isGranted('ROLE_ADMIN');
}
if (!$subject instanceof Publisher) {
throw new \LogicException("Invalid type for voter and attribute.");
}
return $this->checkEntityPermissions($attribute, $subject, $token);
}
public function checkEntityPermissions(string $attribute, Publisher $subject, TokenInterface $token): bool
{
if ($subject->isDeleted() || $subject->isHidden()) {
return false;
}
// ROLE_SUPER_ADMIN inherits ROLE_ADMIN, and will also be included here.
if ($this->security->isGranted('ROLE_ADMIN')) {
return true;
}
if ($attribute !== self::PERMISSION) {
// Don't allow editors or authors to edit or delete publishers.
return false;
}
if ($this->security->isGranted('ROLE_EDITOR')) {
/** @var PublisherPermissionRepository $repo */
$repo = $this->em->getRepository(PublisherPermission::class);
return $repo->hasEditorPermission($token->getUser(), $subject);
}
if ($this->security->isGranted('ROLE_AUTHOR')) {
/** @var PublisherPermissionRepository $repo */
$repo = $this->em->getRepository(PublisherPermission::class);
return $repo->hasAuthorPermissionForPublisher($token->getUser(), $subject);
}
return false;
}
}