src/Security/Voter/OrderVoter.php line 10

Open in your IDE?
  1. <?php
  2. namespace App\Security\Voter;
  3. use App\Entity\Order;
  4. use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
  5. use Symfony\Component\Security\Core\Authorization\Voter\Voter;
  6. use Symfony\Component\Security\Core\User\UserInterface;
  7. class OrderVoter extends Voter
  8. {
  9.     public const VIEW 'ORDER_VIEW';
  10.     public const EDIT 'ORDER_EDIT';
  11.     /**
  12.      * @inheritDoc
  13.      */
  14.     protected function supports(string $attributemixed $subject): bool
  15.     {
  16.         // Only vote on User objects and supported attributes
  17.         return in_array($attribute, [self::VIEWself::EDIT])
  18.             && $subject instanceof Order;
  19.     }
  20.     /**
  21.      * @inheritDoc
  22.      */
  23.     protected function voteOnAttribute(string $attributemixed $subjectTokenInterface $token): bool
  24.     {
  25.         $currentUser $token->getUser();
  26.         if (!$currentUser instanceof UserInterface) {
  27.             return false// not logged in
  28.         }
  29.         /** @var Order $order */
  30.         $order $subject;
  31.         return match ($attribute) {
  32.             self::VIEW => $this->canView($order$currentUser),
  33.             default => false,
  34.         };
  35.     }
  36.     private function canView(Order $orderUserInterface $currentUser): bool
  37.     {
  38.         // Admins can view everyone
  39.         if (in_array('ROLE_ADMIN'$currentUser->getRoles(), true)) {
  40.             return true;
  41.         }
  42.         if (in_array('ROLE_COMMERCIAL'$currentUser->getRoles(), true)) {
  43.             return true;
  44.         }
  45.         // B2B Admins: can view orders of their own customer
  46.         if (in_array('ROLE_B2B_ADMIN'$currentUser->getRoles(), true)) {
  47.             return $order->getCustomer() === $currentUser->getCustomer();
  48.         }
  49.         // B2B Agents: can only view orders they created themselves
  50.         if (in_array('ROLE_B2B_AGENT'$currentUser->getRoles(), true)) {
  51.             return $order->getUser() === $currentUser;
  52.         }
  53.         return false;
  54.     }
  55. }