src/Voter/ShopVoter.php line 11

Open in your IDE?
  1. <?php
  2. namespace App\Voter;
  3. use App\Entity\Customer;
  4. use App\Model\User\User;
  5. use LogicException;
  6. use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
  7. use Symfony\Component\Security\Core\Authorization\Voter\Voter;
  8. class ShopVoter extends Voter
  9. {
  10.     public const SWITCH_SHOP 'switchShop';
  11.     public const BO_VIEW 'bo_view';
  12.     public const VIEW 'view';
  13.     public const EDIT 'edit';
  14.     public const REMOVE_MEMBER 'remove_member';
  15.     public const NEW = 'new';
  16.     /** @var User */
  17.     private $user;
  18.     public function __construct(User $user)
  19.     {
  20.         $this->user $user;
  21.     }
  22.     protected function supports($attribute$shopEntity): bool
  23.     {
  24.         // if the attribute isn't one we support, return false
  25.         if (! in_array($attribute, [
  26.             self::SWITCH_SHOP,
  27.             self::BO_VIEW,
  28.             self::VIEW,
  29.             self::EDIT,
  30.             self::NEW,
  31.             self::REMOVE_MEMBER
  32.         ])
  33.         ) {
  34.             return false;
  35.         }
  36.         if (! $shopEntity instanceof Customer) {
  37.             return false;
  38.         }
  39.         return true;
  40.     }
  41.     protected function voteOnAttribute($attribute$shopEntityTokenInterface $token): bool
  42.     {
  43.         $userEntity $token->getUser();
  44.         $this->user->setEntity($userEntity);
  45.         // Prestachef staff can do all of it
  46.         if ($this->user->isPrestachefStaff()) {
  47.             return true;
  48.         }
  49.         $shop $this->user->getService('shopFactory')->createModel();
  50.         $shop->setEntity($shopEntity);
  51.         switch ($attribute) {
  52.             case self::VIEW:
  53.                 return $this->user->canSeeShop($shop);
  54.             case self::EDIT:
  55.                 return $this->user->canEditShop($shop);
  56.             case self::REMOVE_MEMBER:
  57.                 return $this->user->canRemoveTeamMemberFromShop($shop);
  58.             case self::NEW:
  59.                 return $this->user->canCreateShop();
  60.             case self::SWITCH_SHOP:
  61.                 return $this->user->canSwitchToShop($shop);
  62.             case self::BO_VIEW:
  63.                 // everybody see all customers
  64.                 return $this->user->isPrestachefStaff();
  65.         }
  66.         throw new LogicException('This code should not be reached!');
  67.     }
  68. }