<?php
declare(strict_types=1);
namespace App\Security\Voter\Admin;
use App\Entity\StatefulInterface;
use EasyCorp\Bundle\EasyAdminBundle\Config\Action;
use EasyCorp\Bundle\EasyAdminBundle\Dto\ActionDto;
use EasyCorp\Bundle\EasyAdminBundle\Dto\EntityDto;
use EasyCorp\Bundle\EasyAdminBundle\Security\Permission;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Core\Authorization\AuthorizationCheckerInterface;
use Symfony\Component\Security\Core\Authorization\Voter\Voter;
class StatefulEntityActionVoter extends Voter
{
private AuthorizationCheckerInterface $authorizationChecker;
/**
* StatefulEntityActionVoter constructor.
*/
public function __construct(AuthorizationCheckerInterface $authorizationChecker)
{
$this->authorizationChecker = $authorizationChecker;
}
protected function supports(string $attribute, $subject)
{
if ($attribute !== Permission::EA_EXECUTE_ACTION) {
return false;
}
if (empty($subject['action']) || empty($subject['entity'])) {
return false;
}
$entity = $subject['entity'];
if (!$entity instanceof EntityDto) {
return false;
}
$instance = $entity->getInstance();
if (!$instance instanceof StatefulInterface) {
return false;
}
$action = $subject['action'];
if (!$action instanceof ActionDto) {
return false;
}
return true;
}
protected function voteOnAttribute(string $attribute, $subject, TokenInterface $token)
{
if ($this->authorizationChecker->isGranted('ROLE_SUPER_ADMIN')) {
return true;
}
if (!in_array($subject['action']->getName(), [Action::EDIT, Action::DELETE])) {
return true;
}
/** @var StatefulInterface $entity */
$entity = $subject['entity']->getInstance();
if ($this->authorizationChecker->isGranted('ROLE_EDITOR')) {
return $entity->getStatus()->isEditableByEditor();
}
return false;
}
}