src/Security/Voter/ActionVoter.php line 11

Open in your IDE?
  1. <?php
  2. namespace App\Security\Voter;
  3. use App\Entity\Action;
  4. use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
  5. use Symfony\Component\Security\Core\Authorization\Voter\Voter;
  6. use Symfony\Component\Security\Core\Security;
  7. use Symfony\Component\Security\Core\User\UserInterface;
  8. class ActionVoter extends Voter
  9. {
  10.     public const EDIT 'EDIT';
  11.     public const VIEW 'VIEW';
  12.     /** @var Security */
  13.     private $security;
  14.     public function __construct(Security $security)
  15.     {
  16.         $this->security $security;
  17.     }
  18.     protected function supports(string $attribute$action): bool
  19.     {
  20.         return in_array($attribute, [self::EDITself::VIEW]) && ($action instanceof Action || is_null($action));
  21.     }
  22.     protected function voteOnAttribute(string $attribute$actionTokenInterface $token): bool
  23.     {
  24.         if(is_null($action)) {
  25.             return true;
  26.         }
  27.         $user $token->getUser();
  28.         if (!$user instanceof UserInterface) {
  29.             return false;
  30.         }
  31.         if ($this->security->isGranted('ROLE_SUPERADMIN')) {
  32.             return true;
  33.         }
  34.         switch ($attribute) {
  35.             case self::EDIT:
  36.             case self::VIEW:
  37.                 foreach ($user->getCompanies() as $company) {
  38.                     foreach($company->getCampaigns() as $campaign) {
  39.                         foreach($campaign->getForms() as $form) {
  40.                             foreach($form->getFormActionsSets() as $formActionSet) {
  41.                                 if ($formActionSet->getActions()->contains($action)) {
  42.                                     return true;
  43.                                 }
  44.                             }
  45.                         }
  46.                     }
  47.                 }
  48.             return false;
  49.             break;
  50.         }
  51.         return false;
  52.     }
  53. }