vendor/setono/sylius-gift-card-plugin/src/Security/GiftCardVoter.php line 16

Open in your IDE?
  1. <?php
  2. declare(strict_types=1);
  3. namespace Setono\SyliusGiftCardPlugin\Security;
  4. use LogicException;
  5. use Setono\SyliusGiftCardPlugin\Model\GiftCardInterface;
  6. use Sylius\Component\Core\Model\AdminUserInterface;
  7. use Sylius\Component\Core\Model\ShopUserInterface;
  8. use Sylius\Component\User\Model\UserInterface;
  9. use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
  10. use Symfony\Component\Security\Core\Authorization\Voter\Voter;
  11. use Webmozart\Assert\Assert;
  12. final class GiftCardVoter extends Voter
  13. {
  14.     public const READ 'read';
  15.     protected function supports($attribute$subject): bool
  16.     {
  17.         if (self::READ !== $attribute) {
  18.             return false;
  19.         }
  20.         if (!$subject instanceof GiftCardInterface) {
  21.             return false;
  22.         }
  23.         return true;
  24.     }
  25.     /**
  26.      * @param string $attribute
  27.      * @param GiftCardInterface $subject
  28.      */
  29.     protected function voteOnAttribute($attribute$subjectTokenInterface $token): bool
  30.     {
  31.         /** @var UserInterface|ShopUserInterface|AdminUserInterface|null $user */
  32.         $user $token->getUser();
  33.         if (!$user instanceof UserInterface) {
  34.             return false;
  35.         }
  36.         // Admin can do anything with gift cards
  37.         if ($user instanceof AdminUserInterface) {
  38.             return true;
  39.         }
  40.         Assert::isInstanceOf($userShopUserInterface::class);
  41.         if (self::READ === $attribute) {
  42.             return $this->canRead($subject$user);
  43.         }
  44.         throw new LogicException('This code should not be reached.');
  45.     }
  46.     private function canRead(GiftCardInterface $giftCardShopUserInterface $user): bool
  47.     {
  48.         // Anonymous gift cards can be seen by everyone
  49.         if (null === $giftCard->getCustomer()) {
  50.             return true;
  51.         }
  52.         // GiftCards can only be seen by their proprietary
  53.         return $giftCard->getCustomer() === $user->getCustomer();
  54.     }
  55. }