src/Security/Voter/CustomerVoter.php line 13

Open in your IDE?
  1. <?php
  2. namespace App\Security\Voter;
  3. use App\Entity\Customer;
  4. use App\Entity\CustomerMoral;
  5. use App\Entity\CustomerPhysical;
  6. use App\Entity\Order;
  7. use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
  8. use Symfony\Component\Security\Core\Authorization\Voter\Voter;
  9. use Symfony\Component\Security\Core\User\UserInterface;
  10. class CustomerVoter extends Voter
  11. {
  12.     public const VIEW = 'CUSTOMER_VIEW';
  13.     /**
  14.      * @inheritDoc
  15.      */
  16.     protected function supports(string $attribute, mixed $subject): bool
  17.     {
  18.         // Only vote on User objects and supported attributes
  19.         return in_array($attribute, [self::VIEW])
  20.             && ($subject instanceof CustomerMoral or $subject instanceof CustomerPhysical);
  21.     }
  22.     /**
  23.      * @inheritDoc
  24.      */
  25.     protected function voteOnAttribute(string $attribute, mixed $subject, TokenInterface $token): bool
  26.     {
  27.         $currentUser = $token->getUser();
  28.         if (!$currentUser instanceof UserInterface) {
  29.             return false; // not logged in
  30.         }
  31.         /** @var Order $Customer */
  32.         $customer = $subject;
  33.         return match ($attribute) {
  34.             self::VIEW => $this->canView($customer, $currentUser),
  35.             default => false,
  36.         };
  37.     }
  38.     private function canView(Customer $customer, UserInterface $currentUser): bool
  39.     {
  40.         // Admins can view every thing
  41.         if (in_array('ROLE_SUPER_ADMIN', $currentUser->getRoles(), true)) {
  42.             return true;
  43.         }
  44.         // Admins can view authorized orders
  45.         if (in_array('ROLE_ADMIN', $currentUser->getRoles(), true)) {
  46.             return $this->agentIsAuthorized($customer, $currentUser);
  47.         }
  48.         if (in_array('ROLE_COMMERCIAL', $currentUser->getRoles(), true)) {
  49.             return $this->agentIsAuthorized($customer, $currentUser);
  50.         }
  51.         if (in_array('ROLE_BRANCH', $currentUser->getRoles(), true)) {
  52.             return $this->agentIsAuthorized($customer, $currentUser);
  53.         }
  54.         return false;
  55.     }
  56.     private function agentIsAuthorized(Customer $customer, UserInterface $currentUser)
  57.     {
  58.         $personal = $currentUser->getPersonal();
  59.         if (!$personal) {
  60.             return false;
  61.         }
  62.         return $personal->getAuthAgencies()->contains($customer->getAgency());
  63.     }
  64. }