src/Security/Voter/InvoiceVoter.php line 13

Open in your IDE?
  1. <?php
  2. namespace App\Security\Voter;
  3. use App\Entity\Invoice;
  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 Invoice entities based on client ownership.
  9.  */
  10. class InvoiceVoter 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 Invoice;
  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 Invoice $invoice */
  32.         $invoice $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 invoice (through order)
  39.         $invoiceClient $invoice->getClient();
  40.         if (!$invoiceClient) {
  41.             return false;
  42.         }
  43.         // Check if both belong to the same client
  44.         if ($userClient->getId() !== $invoiceClient->getId()) {
  45.             return false;
  46.         }
  47.         // User needs at least ROLE_MANAGER to access invoices
  48.         return in_array('ROLE_MANAGER'$user->getRoles(), true);
  49.     }
  50. }