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

Open in your IDE?
  1. <?php
  2. declare(strict_types=1);
  3. namespace Sylius\InvoicingPlugin\Security\Voter;
  4. use Sylius\Component\Core\Model\AdminUserInterface;
  5. use Sylius\Component\Core\Model\ShopUserInterface;
  6. use Sylius\Component\Core\Repository\OrderRepositoryInterface;
  7. use Sylius\Component\User\Model\UserInterface;
  8. use Sylius\InvoicingPlugin\Entity\InvoiceInterface;
  9. use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
  10. use Symfony\Component\Security\Core\Authorization\Voter\Voter;
  11. use Webmozart\Assert\Assert;
  12. final class InvoiceVoter extends Voter
  13. {
  14.     public const ACCESS 'access';
  15.     private const ATTRIBUTES = [self::ACCESS];
  16.     /** @var OrderRepositoryInterface */
  17.     private $orderRepository;
  18.     public function __construct(OrderRepositoryInterface $orderRepository)
  19.     {
  20.         $this->orderRepository $orderRepository;
  21.     }
  22.     protected function supports($attribute$subject): bool
  23.     {
  24.         if (!in_array($attributeself::ATTRIBUTEStrue)) {
  25.             return false;
  26.         }
  27.         if (!$subject instanceof InvoiceInterface) {
  28.             return false;
  29.         }
  30.         return true;
  31.     }
  32.     protected function voteOnAttribute($attribute$subjectTokenInterface $token): bool
  33.     {
  34.         /** @var InvoiceInterface $subject */
  35.         Assert::isInstanceOf($subjectInvoiceInterface::class);
  36.         $user $token->getUser();
  37.         if (!$user instanceof UserInterface) {
  38.             return false;
  39.         }
  40.         switch ($attribute) {
  41.             case self::ACCESS:
  42.                 return $this->canAccess($user$subject);
  43.             default:
  44.                 throw new \LogicException(sprintf('Unknown attribute "%s" passed.'$attribute));
  45.         }
  46.     }
  47.     private function canAccess(UserInterface $userInvoiceInterface $invoice): bool
  48.     {
  49.         if ($user instanceof AdminUserInterface) {
  50.             return true;
  51.         }
  52.         if ($user instanceof ShopUserInterface) {
  53.             return null !== $this->orderRepository->findOneByNumberAndCustomer($invoice->orderNumber(), $user->getCustomer());
  54.         }
  55.         return false;
  56.     }
  57. }