vendor/sylius/invoicing-plugin/src/Security/Voter/InvoiceVoter.php line 26

Open in your IDE?
  1. <?php
  2. /*
  3.  * This file is part of the Sylius package.
  4.  *
  5.  * (c) Paweł Jędrzejewski
  6.  *
  7.  * For the full copyright and license information, please view the LICENSE
  8.  * file that was distributed with this source code.
  9.  */
  10. declare(strict_types=1);
  11. namespace Sylius\InvoicingPlugin\Security\Voter;
  12. use Sylius\Component\Core\Model\AdminUserInterface;
  13. use Sylius\Component\Core\Model\CustomerInterface;
  14. use Sylius\Component\Core\Model\ShopUserInterface;
  15. use Sylius\Component\Core\Repository\OrderRepositoryInterface;
  16. use Sylius\Component\User\Model\UserInterface;
  17. use Sylius\InvoicingPlugin\Entity\InvoiceInterface;
  18. use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
  19. use Symfony\Component\Security\Core\Authorization\Voter\Voter;
  20. use Webmozart\Assert\Assert;
  21. final class InvoiceVoter extends Voter
  22. {
  23.     public const ACCESS 'access';
  24.     private const ATTRIBUTES = [self::ACCESS];
  25.     private OrderRepositoryInterface $orderRepository;
  26.     public function __construct(OrderRepositoryInterface $orderRepository)
  27.     {
  28.         $this->orderRepository $orderRepository;
  29.     }
  30.     protected function supports($attribute$subject): bool
  31.     {
  32.         if (!in_array($attributeself::ATTRIBUTEStrue)) {
  33.             return false;
  34.         }
  35.         if (!$subject instanceof InvoiceInterface) {
  36.             return false;
  37.         }
  38.         return true;
  39.     }
  40.     /**
  41.      * @param mixed $attribute
  42.      * @param mixed $subject
  43.      */
  44.     protected function voteOnAttribute($attribute$subjectTokenInterface $token): bool
  45.     {
  46.         Assert::isInstanceOf($subjectInvoiceInterface::class);
  47.         $user $token->getUser();
  48.         if (!$user instanceof UserInterface) {
  49.             return false;
  50.         }
  51.         switch ($attribute) {
  52.             case self::ACCESS:
  53.                 return $this->canAccess($user$subject);
  54.             default:
  55.                 throw new \LogicException(sprintf('Unknown attribute "%s" passed.'$attribute));
  56.         }
  57.     }
  58.     private function canAccess(UserInterface $userInvoiceInterface $invoice): bool
  59.     {
  60.         if ($user instanceof AdminUserInterface) {
  61.             return true;
  62.         }
  63.         if ($user instanceof ShopUserInterface) {
  64.             $customer $user->getCustomer();
  65.             Assert::isInstanceOf($customerCustomerInterface::class);
  66.             return null !== $this->orderRepository->findOneByNumberAndCustomer($invoice->orderNumber(), $customer);
  67.         }
  68.         return false;
  69.     }
  70. }