src/App/Api/Security/Voter/UserActionsVoter.php line 13

Open in your IDE?
  1. <?php
  2. declare(strict_types=1);
  3. namespace App\Api\Security\Voter;
  4. use App\Api\Entity\User;
  5. use App\Api\Entity\UserAbstract;
  6. use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
  7. use Symfony\Component\Security\Core\Authorization\Voter\Voter;
  8. use Symfony\Component\Security\Core\User\UserInterface;
  9. class UserActionsVoter extends Voter
  10. {
  11.     public const DELETE 'delete';
  12.     public const UPDATE 'update';
  13.     protected function supports($attribute$subject)
  14.     {
  15.         if (!in_array($attribute, [self::DELETEself::UPDATE])) {
  16.             return false;
  17.         }
  18.         if (!$subject instanceof UserAbstract) {
  19.             return false;
  20.         }
  21.         return true;
  22.     }
  23.     protected function voteOnAttribute($attribute$subjectTokenInterface $token)
  24.     {
  25.         $authenticatedUser $token->getUser();
  26.         if (!$authenticatedUser instanceof UserAbstract) {
  27.             return false;
  28.         }
  29.         /** @var User $post */
  30.         $userFromRequest $subject;
  31.         switch ($attribute) {
  32.             case self::DELETE:
  33.                 return $this->canDelete($userFromRequest);
  34.             case self::UPDATE:
  35.                 return $this->canUpdate($userFromRequest$authenticatedUser);
  36.         }
  37.     }
  38.     private function canDelete(UserInterface $user): bool
  39.     {
  40.         return $user->isTdc1Manager();
  41.     }
  42.     private function canUpdate(UserInterface $userFromRequestUserInterface $authenticatedUser): bool
  43.     {
  44.         return $userFromRequest->getId() === $authenticatedUser->getId();
  45.     }
  46. }