src/Security/Voter/Admin/StatefulEntityActionVoter.php line 16

Open in your IDE?
  1. <?php
  2. declare(strict_types=1);
  3. namespace App\Security\Voter\Admin;
  4. use App\Entity\StatefulInterface;
  5. use EasyCorp\Bundle\EasyAdminBundle\Config\Action;
  6. use EasyCorp\Bundle\EasyAdminBundle\Dto\ActionDto;
  7. use EasyCorp\Bundle\EasyAdminBundle\Dto\EntityDto;
  8. use EasyCorp\Bundle\EasyAdminBundle\Security\Permission;
  9. use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
  10. use Symfony\Component\Security\Core\Authorization\AuthorizationCheckerInterface;
  11. use Symfony\Component\Security\Core\Authorization\Voter\Voter;
  12. class StatefulEntityActionVoter extends Voter
  13. {
  14.     private AuthorizationCheckerInterface $authorizationChecker;
  15.     /**
  16.      * StatefulEntityActionVoter constructor.
  17.      */
  18.     public function __construct(AuthorizationCheckerInterface $authorizationChecker)
  19.     {
  20.         $this->authorizationChecker $authorizationChecker;
  21.     }
  22.     protected function supports(string $attribute$subject)
  23.     {
  24.         if ($attribute !== Permission::EA_EXECUTE_ACTION) {
  25.             return false;
  26.         }
  27.         if (empty($subject['action']) || empty($subject['entity'])) {
  28.             return false;
  29.         }
  30.         $entity $subject['entity'];
  31.         if (!$entity instanceof EntityDto) {
  32.             return false;
  33.         }
  34.         $instance $entity->getInstance();
  35.         if (!$instance instanceof StatefulInterface) {
  36.             return false;
  37.         }
  38.         $action $subject['action'];
  39.         if (!$action instanceof ActionDto) {
  40.             return false;
  41.         }
  42.         return true;
  43.     }
  44.     protected function voteOnAttribute(string $attribute$subjectTokenInterface $token)
  45.     {
  46.         if ($this->authorizationChecker->isGranted('ROLE_SUPER_ADMIN')) {
  47.             return true;
  48.         }
  49.         if (!in_array($subject['action']->getName(), [Action::EDITAction::DELETE])) {
  50.             return true;
  51.         }
  52.         /** @var StatefulInterface $entity */
  53.         $entity $subject['entity']->getInstance();
  54.         if ($this->authorizationChecker->isGranted('ROLE_EDITOR')) {
  55.             return $entity->getStatus()->isEditableByEditor();
  56.         }
  57.         return false;
  58.     }
  59. }