src/Security/Voter/SwitchToUserVoter.php line 9

  1. <?php
  2. namespace App\Security\Voter;
  3. use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
  4. use Symfony\Component\Security\Core\Authorization\Voter\Voter;
  5. use Symfony\Component\Security\Core\User\UserInterface;
  6. class SwitchToUserVoter extends Voter
  7. {
  8.     protected function supports($attribute$subject): bool
  9.     {
  10.         return in_array($attribute, ['CAN_SWITCH_USER'])
  11.             && $subject instanceof UserInterface;
  12.     }
  13.     protected function voteOnAttribute($attribute$subjectTokenInterface $token): bool
  14.     {
  15.         $user $token->getUser();
  16.         if (!$user instanceof UserInterface || !$subject instanceof UserInterface) {
  17.             return false;
  18.         }
  19.         if ($subject->getCreator() != $user) {
  20.             $checkUserAncestor = function($userRecord) use (&$checkUserAncestor) {
  21.                 if ($userRecord->getCreator()) {
  22.                     return $checkUserAncestor($userRecord->getCreator());
  23.                 } else {
  24.                     return $userRecord;
  25.                 }
  26.             };
  27.             if ($checkUserAncestor($subject) == $user) {
  28.                 return true;
  29.             }
  30.             return $user->getControlling()->includes($subject);
  31.         }
  32.         return true;
  33.     }
  34. }