vendor/bitbag/wishlist-plugin/src/Voter/WishlistVoter.php line 19

Open in your IDE?
  1. <?php
  2. /*
  3.  * This file was created by developers working at BitBag
  4.  * Do you need more information about us and what we do? Visit our https://bitbag.io website!
  5.  * We are hiring developers from all over the world. Join us and start your new, exciting adventure and become part of us: https://bitbag.io/career
  6. */
  7. declare(strict_types=1);
  8. namespace BitBag\SyliusWishlistPlugin\Voter;
  9. use BitBag\SyliusWishlistPlugin\Entity\WishlistInterface;
  10. use Sylius\Component\Core\Model\ShopUserInterface;
  11. use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
  12. use Symfony\Component\Security\Core\Authorization\Voter\Voter;
  13. use Symfony\Component\Security\Core\Security;
  14. final class WishlistVoter extends Voter
  15. {
  16.     public const UPDATE 'update';
  17.     public const DELETE 'delete';
  18.     private Security $security;
  19.     public function __construct(Security $security)
  20.     {
  21.         $this->security $security;
  22.     }
  23.     protected function supports($attribute$subject): bool
  24.     {
  25.         $attributes = [
  26.             self::UPDATE,
  27.             self::DELETE,
  28.         ];
  29.         if (!in_array($attribute$attributestrue) ||
  30.             !$subject instanceof WishlistInterface) {
  31.             return false;
  32.         }
  33.         return true;
  34.     }
  35.     /** @param string $attribute */
  36.     protected function voteOnAttribute(
  37.         $attribute,
  38.         $subject,
  39.         TokenInterface $token
  40.     ): bool {
  41.         $user $token->getUser();
  42.         if (!$user instanceof ShopUserInterface) {
  43.             $user null;
  44.         }
  45.         /** @var WishlistInterface $wishlist */
  46.         $wishlist $subject;
  47.         switch ($attribute) {
  48.             case self::UPDATE:
  49.                 return $this->canUpdate($wishlist$user);
  50.             case self::DELETE:
  51.                 return $this->canDelete($wishlist$user);
  52.         }
  53.         throw new \LogicException(sprintf('Unsupported attribute: "%s"'$attribute));
  54.     }
  55.     public function canUpdate(WishlistInterface $wishlist, ?ShopUserInterface $user): bool
  56.     {
  57.         if (!$this->security->isGranted('ROLE_USER') && null === $wishlist->getShopUser()) {
  58.             return true;
  59.         }
  60.         if ($this->security->isGranted('ROLE_USER') && $wishlist->getShopUser() === $user) {
  61.             return true;
  62.         }
  63.         return false;
  64.     }
  65.     public function canDelete(WishlistInterface $wishlist, ?ShopUserInterface $user): bool
  66.     {
  67.         return $this->canUpdate($wishlist$user);
  68.     }
  69. }