src/Security/Voter/OrderVoter.php line 13

Open in your IDE?
  1. <?php
  2. namespace App\Security\Voter;
  3. use App\Entity\Order;
  4. use App\User\Entity\User;
  5. use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
  6. use Symfony\Component\Security\Core\Authorization\Voter\Voter;
  7. /**
  8.  * Security voter to control access to Order entities based on client ownership.
  9.  */
  10. class OrderVoter extends Voter
  11. {
  12.     public const VIEW 'view';
  13.     public const EDIT 'edit';
  14.     public const DELETE 'delete';
  15.     protected function supports(string $attribute$subject): bool
  16.     {
  17.         return in_array($attribute, [self::VIEWself::EDITself::DELETE], true)
  18.             && $subject instanceof Order;
  19.     }
  20.     protected function voteOnAttribute(string $attribute$subjectTokenInterface $token): bool
  21.     {
  22.         $user $token->getUser();
  23.         // User must be logged in
  24.         if (!$user instanceof User) {
  25.             return false;
  26.         }
  27.         // ROLE_SUPER_USER can access everything
  28.         if (in_array('ROLE_SUPER_USER'$user->getRoles(), true)) {
  29.             return true;
  30.         }
  31.         /** @var Order $order */
  32.         $order $subject;
  33.         // Get the client of the current user
  34.         $userClient $user->getClient();
  35.         if (!$userClient) {
  36.             return false;
  37.         }
  38.         // Get the client of the order
  39.         $orderClient $order->getClient();
  40.         if (!$orderClient) {
  41.             return false;
  42.         }
  43.         // Check if both belong to the same client
  44.         if ($userClient->getId() !== $orderClient->getId()) {
  45.             return false;
  46.         }
  47.         // User needs at least ROLE_MANAGER or ROLE_ADMIN to access orders
  48.         return in_array('ROLE_MANAGER'$user->getRoles(), true)
  49.             || in_array('ROLE_ADMIN'$user->getRoles(), true);
  50.     }
  51. }