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.     /** @var OrderRepositoryInterface */
  26.     private $orderRepository;
  27.     public function __construct(OrderRepositoryInterface $orderRepository)
  28.     {
  29.         $this->orderRepository $orderRepository;
  30.     }
  31.     protected function supports($attribute$subject): bool
  32.     {
  33.         if (!in_array($attributeself::ATTRIBUTEStrue)) {
  34.             return false;
  35.         }
  36.         if (!$subject instanceof InvoiceInterface) {
  37.             return false;
  38.         }
  39.         return true;
  40.     }
  41.     /**
  42.      * @param mixed $attribute
  43.      * @param mixed $subject
  44.      */
  45.     protected function voteOnAttribute($attribute$subjectTokenInterface $token): bool
  46.     {
  47.         Assert::isInstanceOf($subjectInvoiceInterface::class);
  48.         $user $token->getUser();
  49.         if (!$user instanceof UserInterface) {
  50.             return false;
  51.         }
  52.         switch ($attribute) {
  53.             case self::ACCESS:
  54.                 return $this->canAccess($user$subject);
  55.             default:
  56.                 throw new \LogicException(sprintf('Unknown attribute "%s" passed.'$attribute));
  57.         }
  58.     }
  59.     private function canAccess(UserInterface $userInvoiceInterface $invoice): bool
  60.     {
  61.         if ($user instanceof AdminUserInterface) {
  62.             return true;
  63.         }
  64.         if ($user instanceof ShopUserInterface) {
  65.             $customer $user->getCustomer();
  66.             Assert::isInstanceOf($customerCustomerInterface::class);
  67.             return null !== $this->orderRepository->findOneByNumberAndCustomer($invoice->orderNumber(), $customer);
  68.         }
  69.         return false;
  70.     }
  71. }