src/Security/Voter/MessagingSubjectVoter.php line 11

Open in your IDE?
  1. <?php
  2. namespace App\Security\Voter;
  3. use App\Entity\Messaging\Subject;
  4. use App\Entity\User;
  5. use App\Messaging\ContactFlow\FlowManager;
  6. use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
  7. use Symfony\Component\Security\Core\Authorization\Voter\Voter;
  8. class MessagingSubjectVoter extends Voter
  9. {
  10.     public const VIEW 'VIEW';
  11.     /** @var FlowManager */
  12.     protected $flowManager;
  13.     /**
  14.      * MessagingSubjectVoter constructor.
  15.      */
  16.     public function __construct(FlowManager $flowManager)
  17.     {
  18.         $this->flowManager $flowManager;
  19.     }
  20.     /**
  21.      * @param string $attribute
  22.      * @param mixed  $subject
  23.      *
  24.      * @return bool
  25.      */
  26.     protected function supports($attribute$subject)
  27.     {
  28.         if ($attribute !== static::VIEW) {
  29.             return false;
  30.         }
  31.         if (!$subject instanceof Subject) {
  32.             return false;
  33.         }
  34.         return true;
  35.     }
  36.     /**
  37.      * @param string $attribute
  38.      * @param mixed  $subject
  39.      *
  40.      * @return bool
  41.      */
  42.     protected function voteOnAttribute($attribute$subjectTokenInterface $token)
  43.     {
  44.         $user $token->getUser();
  45.         if (!$user instanceof User) {
  46.             return false;
  47.         }
  48.         if (static::VIEW === $attribute) {
  49.             return $this->canView($subject$user);
  50.         }
  51.         return false;
  52.     }
  53.     protected function canView(Subject $subjectUser $user): bool
  54.     {
  55.         $requiredRoles $this->flowManager->getRequiredRoles($subject);
  56.         if (== count($requiredRoles)) {
  57.             return true;
  58.         }
  59.         foreach ($requiredRoles as $role) {
  60.             if ($user->hasRole($role)) {
  61.                 return true;
  62.             }
  63.         }
  64.         return false;
  65.     }
  66. }