src/Voter/OrderVoter.php line 12

Open in your IDE?
  1. <?php
  2. namespace App\Voter;
  3. use App\Entity\Order;
  4. use App\Model\OrderFactory;
  5. use App\Model\User\User;
  6. use LogicException;
  7. use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
  8. use Symfony\Component\Security\Core\Authorization\Voter\Voter;
  9. class OrderVoter extends Voter
  10. {
  11.     public const VIEW 'view';
  12.     public const BO_VIEW 'bo_view';
  13.     public const EDIT 'edit';
  14.     public const CANCEL 'cancel';
  15.     public const BUY 'buy';
  16.     private $orderFactory;
  17.     private $user;
  18.     public function __construct(OrderFactory $orderFactoryUser $user)
  19.     {
  20.         $this->orderFactory $orderFactory;
  21.         $this->user         $user;
  22.     }
  23.     protected function supports($attribute$orderEntity): bool
  24.     {
  25.         // if the attribute isn't one we support, return false
  26.         if (! in_array($attribute, [
  27.             self::VIEW,
  28.             self::BO_VIEW,
  29.             self::EDIT,
  30.             self::CANCEL,
  31.             self::BUY,
  32.         ])
  33.         ) {
  34.             return false;
  35.         }
  36.         if (! $orderEntity instanceof Order) {
  37.             return false;
  38.         }
  39.         return true;
  40.     }
  41.     protected function voteOnAttribute($attribute$orderEntityTokenInterface $token): bool
  42.     {
  43.         $roles      = [];
  44.         $userEntity $token->getUser();
  45.         if ($userEntity != 'anon.') {
  46.             $this->user->setEntity($userEntity);
  47.             $roles $userEntity->getRoles();
  48.         }
  49.         $order $this->orderFactory->createModel();
  50.         $order->setEntity($orderEntity);
  51.         if (in_array('ROLE_ADMIN'$roles)) {
  52.             return true;
  53.         }
  54.         switch ($attribute) {
  55.             case self::VIEW:
  56.                 return $order->canBeViewedBy($this->user);
  57.             case self::EDIT:
  58.                 return $order->canBeEditedBy($this->user);
  59.             case self::BO_VIEW:
  60.                 return $order->canBeBoViewedBy($this->user);
  61.             case self::CANCEL:
  62.                 return $order->canBeCancelledBy($this->user);
  63.         }
  64.         throw new LogicException('This code should not be reached!');
  65.     }
  66. }