src/Profile/Security/Voter/HorseVoter.php line 13

Open in your IDE?
  1. <?php
  2. namespace App\Profile\Security\Voter;
  3. use App\Horse\Service\HorseService;
  4. use App\Profile\Model\Profile;
  5. use App\Profile\Model\ProfileRoles;
  6. use Pimcore\Model\DataObject\Horse;
  7. use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
  8. use Symfony\Component\Security\Core\Authorization\Voter\Voter;
  9. use Symfony\Component\Security\Core\Security;
  10. class HorseVoter extends Voter
  11. {
  12.   public const CREATE 'profile.horse.create';
  13.   public function __construct(protected Security $security, protected HorseService $horseService)
  14.   {
  15.   }
  16.   protected function supports(string $attribute$subject null): bool
  17.   {
  18.     if (!in_array($attribute, [self::CREATE])) {
  19.       return false;
  20.     }
  21.     return true;
  22.   }
  23.   protected function voteOnAttribute(string $attribute$subject nullTokenInterface $token null): bool
  24.   {
  25.     if (!$token) {
  26.       throw new \Exception('TokenInterface $token is not injected');
  27.     }
  28.     $user $token->getUser();
  29.     if (!$user instanceof Profile) {
  30.       return false;
  31.     }
  32.     switch ($attribute) {
  33.       case self::CREATE:
  34.         return $this->canCreate($user);
  35.     }
  36.     throw new \LogicException(sprintf('Attribute `%s` not supported by horse object'$attribute));
  37.   }
  38.   protected function canCreate(Profile $profile): bool
  39.   {
  40.     // Only Horse Club Members can create Horses
  41.     if (!$this->security->isGranted(ProfileRoles::ROLE_CLUB_HORSE)) {
  42.       return false;
  43.     }
  44.     return true;
  45.   }
  46. }