vendor/shopware/core/System/SalesChannel/Context/SalesChannelContextFactory.php line 61

  1. <?php declare(strict_types=1);
  2. namespace Shopware\Core\System\SalesChannel\Context;
  3. use Shopware\Core\Checkout\Cart\Delivery\Struct\ShippingLocation;
  4. use Shopware\Core\Checkout\Cart\Price\Struct\CartPrice;
  5. use Shopware\Core\Checkout\Cart\Tax\TaxDetector;
  6. use Shopware\Core\Checkout\Customer\Aggregate\CustomerAddress\CustomerAddressEntity;
  7. use Shopware\Core\Checkout\Customer\CustomerEntity;
  8. use Shopware\Core\Checkout\Payment\Exception\UnknownPaymentMethodException;
  9. use Shopware\Core\Checkout\Payment\PaymentMethodEntity;
  10. use Shopware\Core\Framework\Api\Context\SalesChannelApiSource;
  11. use Shopware\Core\Framework\Context;
  12. use Shopware\Core\Framework\DataAbstractionLayer\EntityRepository;
  13. use Shopware\Core\Framework\DataAbstractionLayer\Pricing\CashRoundingConfig;
  14. use Shopware\Core\Framework\DataAbstractionLayer\Search\Criteria;
  15. use Shopware\Core\Framework\DataAbstractionLayer\Search\Filter\EqualsFilter;
  16. use Shopware\Core\Framework\DataAbstractionLayer\Search\Filter\MultiFilter;
  17. use Shopware\Core\Framework\Log\Package;
  18. use Shopware\Core\Framework\Plugin\Exception\DecorationPatternException;
  19. use Shopware\Core\System\Currency\Aggregate\CurrencyCountryRounding\CurrencyCountryRoundingEntity;
  20. use Shopware\Core\System\SalesChannel\BaseContext;
  21. use Shopware\Core\System\SalesChannel\Event\SalesChannelContextPermissionsChangedEvent;
  22. use Shopware\Core\System\SalesChannel\SalesChannelContext;
  23. use Shopware\Core\System\Tax\Aggregate\TaxRule\TaxRuleCollection;
  24. use Shopware\Core\System\Tax\Aggregate\TaxRule\TaxRuleEntity;
  25. use Shopware\Core\System\Tax\TaxCollection;
  26. use Shopware\Core\System\Tax\TaxRuleType\TaxRuleTypeFilterInterface;
  27. use Symfony\Component\EventDispatcher\EventDispatcherInterface;
  28. use function array_unique;
  29. #[Package('sales-channel')]
  30. class SalesChannelContextFactory extends AbstractSalesChannelContextFactory
  31. {
  32.     /**
  33.      * @internal
  34.      *
  35.      * @param iterable<TaxRuleTypeFilterInterface> $taxRuleTypeFilter
  36.      */
  37.     public function __construct(
  38.         private readonly EntityRepository $customerRepository,
  39.         private readonly EntityRepository $customerGroupRepository,
  40.         private readonly EntityRepository $addressRepository,
  41.         private readonly EntityRepository $paymentMethodRepository,
  42.         private readonly TaxDetector $taxDetector,
  43.         private readonly iterable $taxRuleTypeFilter,
  44.         private readonly EventDispatcherInterface $eventDispatcher,
  45.         private readonly EntityRepository $currencyCountryRepository,
  46.         private readonly AbstractBaseContextFactory $baseContextFactory
  47.     ) {
  48.     }
  49.     public function getDecorated(): AbstractSalesChannelContextFactory
  50.     {
  51.         throw new DecorationPatternException(self::class);
  52.     }
  53.     public function create(string $tokenstring $salesChannelId, array $options = []): SalesChannelContext
  54.     {
  55.         // we split the context generation to allow caching of the base context
  56.         $base $this->baseContextFactory->create($salesChannelId$options);
  57.         // customer
  58.         $customer null;
  59.         if (\array_key_exists(SalesChannelContextService::CUSTOMER_ID$options) && $options[SalesChannelContextService::CUSTOMER_ID] !== null) {
  60.             //load logged in customer and set active addresses
  61.             $customer $this->loadCustomer($options$base->getContext());
  62.         }
  63.         $shippingLocation $base->getShippingLocation();
  64.         if ($customer) {
  65.             /** @var CustomerAddressEntity $activeShippingAddress */
  66.             $activeShippingAddress $customer->getActiveShippingAddress();
  67.             $shippingLocation ShippingLocation::createFromAddress($activeShippingAddress);
  68.         }
  69.         $customerGroup $base->getCurrentCustomerGroup();
  70.         if ($customer) {
  71.             $criteria = new Criteria([$customer->getGroupId()]);
  72.             $criteria->setTitle('context-factory::customer-group');
  73.             $customerGroup $this->customerGroupRepository->search($criteria$base->getContext())->first() ?? $customerGroup;
  74.         }
  75.         //loads tax rules based on active customer and delivery address
  76.         $taxRules $this->getTaxRules($base$customer$shippingLocation);
  77.         //detect active payment method, first check if checkout defined other payment method, otherwise validate if customer logged in, at least use shop default
  78.         $payment $this->getPaymentMethod($options$base$customer);
  79.         [$itemRounding$totalRounding] = $this->getCashRounding($base$shippingLocation);
  80.         $context = new Context(
  81.             $base->getContext()->getSource(),
  82.             [],
  83.             $base->getCurrencyId(),
  84.             $base->getContext()->getLanguageIdChain(),
  85.             $base->getContext()->getVersionId(),
  86.             $base->getCurrency()->getFactor(),
  87.             true,
  88.             CartPrice::TAX_STATE_GROSS,
  89.             $itemRounding
  90.         );
  91.         $salesChannelContext = new SalesChannelContext(
  92.             $context,
  93.             $token,
  94.             $options[SalesChannelContextService::DOMAIN_ID] ?? null,
  95.             $base->getSalesChannel(),
  96.             $base->getCurrency(),
  97.             $customerGroup,
  98.             $taxRules,
  99.             $payment,
  100.             $base->getShippingMethod(),
  101.             $shippingLocation,
  102.             $customer,
  103.             $itemRounding,
  104.             $totalRounding
  105.         );
  106.         if (\array_key_exists(SalesChannelContextService::PERMISSIONS$options)) {
  107.             $salesChannelContext->setPermissions($options[SalesChannelContextService::PERMISSIONS]);
  108.             $event = new SalesChannelContextPermissionsChangedEvent($salesChannelContext$options[SalesChannelContextService::PERMISSIONS]);
  109.             $this->eventDispatcher->dispatch($event);
  110.             $salesChannelContext->lockPermissions();
  111.         }
  112.         $salesChannelContext->setTaxState($this->taxDetector->getTaxState($salesChannelContext));
  113.         return $salesChannelContext;
  114.     }
  115.     private function getTaxRules(BaseContext $context, ?CustomerEntity $customerShippingLocation $shippingLocation): TaxCollection
  116.     {
  117.         $taxes $context->getTaxRules()->getElements();
  118.         foreach ($taxes as $tax) {
  119.             $taxRules $tax->getRules();
  120.             if ($taxRules === null) {
  121.                 continue;
  122.             }
  123.             $taxRules $taxRules->filter(function (TaxRuleEntity $taxRule) use ($customer$shippingLocation) {
  124.                 foreach ($this->taxRuleTypeFilter as $ruleTypeFilter) {
  125.                     if ($ruleTypeFilter->match($taxRule$customer$shippingLocation)) {
  126.                         return true;
  127.                     }
  128.                 }
  129.                 return false;
  130.             });
  131.             $taxRules->sortByTypePosition();
  132.             $taxRule $taxRules->first();
  133.             $matchingRules = new TaxRuleCollection();
  134.             if ($taxRule) {
  135.                 $matchingRules->add($taxRule);
  136.             }
  137.             $tax->setRules($matchingRules);
  138.         }
  139.         return new TaxCollection($taxes);
  140.     }
  141.     /**
  142.      * @group not-deterministic
  143.      * NEXT-21735 - This is covered randomly
  144.      *
  145.      * @codeCoverageIgnore
  146.      *
  147.      * @param array<string, mixed> $options
  148.      */
  149.     private function getPaymentMethod(array $optionsBaseContext $context, ?CustomerEntity $customer): PaymentMethodEntity
  150.     {
  151.         if ($customer === null || isset($options[SalesChannelContextService::PAYMENT_METHOD_ID])) {
  152.             return $context->getPaymentMethod();
  153.         }
  154.         $id $customer->getLastPaymentMethodId() ?? $customer->getDefaultPaymentMethodId();
  155.         if ($id === $context->getPaymentMethod()->getId()) {
  156.             // NEXT-21735 - does not execute on every test run
  157.             return $context->getPaymentMethod();
  158.         }
  159.         $criteria = new Criteria([$id]);
  160.         $criteria->addAssociation('media');
  161.         $criteria->setTitle('context-factory::payment-method');
  162.         /** @var PaymentMethodEntity|null $paymentMethod */
  163.         $paymentMethod $this->paymentMethodRepository->search($criteria$context->getContext())->get($id);
  164.         if (!$paymentMethod) {
  165.             throw new UnknownPaymentMethodException($id);
  166.         }
  167.         return $paymentMethod;
  168.     }
  169.     /**
  170.      * @param array<string, mixed> $options
  171.      */
  172.     private function loadCustomer(array $optionsContext $context): ?CustomerEntity
  173.     {
  174.         $addressIds = [];
  175.         $customerId $options[SalesChannelContextService::CUSTOMER_ID];
  176.         $criteria = new Criteria([$customerId]);
  177.         $criteria->setTitle('context-factory::customer');
  178.         $criteria->addAssociation('salutation');
  179.         $criteria->addAssociation('defaultPaymentMethod');
  180.         /** @var SalesChannelApiSource $source */
  181.         $source $context->getSource();
  182.         $criteria->addFilter(new MultiFilter(MultiFilter::CONNECTION_OR, [
  183.             new EqualsFilter('customer.boundSalesChannelId'null),
  184.             new EqualsFilter('customer.boundSalesChannelId'$source->getSalesChannelId()),
  185.         ]));
  186.         /** @var CustomerEntity|null $customer */
  187.         $customer $this->customerRepository->search($criteria$context)->get($customerId);
  188.         if (!$customer) {
  189.             return null;
  190.         }
  191.         $activeBillingAddressId $options[SalesChannelContextService::BILLING_ADDRESS_ID] ?? $customer->getDefaultBillingAddressId();
  192.         $activeShippingAddressId $options[SalesChannelContextService::SHIPPING_ADDRESS_ID] ?? $customer->getDefaultShippingAddressId();
  193.         $addressIds[] = $activeBillingAddressId;
  194.         $addressIds[] = $activeShippingAddressId;
  195.         $addressIds[] = $customer->getDefaultBillingAddressId();
  196.         $addressIds[] = $customer->getDefaultShippingAddressId();
  197.         $criteria = new Criteria(array_unique($addressIds));
  198.         $criteria->setTitle('context-factory::addresses');
  199.         $criteria->addAssociation('salutation');
  200.         $criteria->addAssociation('country');
  201.         $criteria->addAssociation('countryState');
  202.         $addresses $this->addressRepository->search($criteria$context);
  203.         /** @var CustomerAddressEntity $activeBillingAddress */
  204.         $activeBillingAddress $addresses->get($activeBillingAddressId);
  205.         $customer->setActiveBillingAddress($activeBillingAddress);
  206.         /** @var CustomerAddressEntity $activeShippingAddress */
  207.         $activeShippingAddress $addresses->get($activeShippingAddressId);
  208.         $customer->setActiveShippingAddress($activeShippingAddress);
  209.         /** @var CustomerAddressEntity $defaultBillingAddress */
  210.         $defaultBillingAddress $addresses->get($customer->getDefaultBillingAddressId());
  211.         $customer->setDefaultBillingAddress($defaultBillingAddress);
  212.         /** @var CustomerAddressEntity $defaultShippingAddress */
  213.         $defaultShippingAddress $addresses->get($customer->getDefaultShippingAddressId());
  214.         $customer->setDefaultShippingAddress($defaultShippingAddress);
  215.         return $customer;
  216.     }
  217.     /**
  218.      * @return CashRoundingConfig[]
  219.      *
  220.      * @group not-deterministic
  221.      * NEXT-21735 - This is covered randomly
  222.      *
  223.      * @codeCoverageIgnore
  224.      */
  225.     private function getCashRounding(BaseContext $contextShippingLocation $shippingLocation): array
  226.     {
  227.         if ($context->getShippingLocation()->getCountry()->getId() === $shippingLocation->getCountry()->getId()) {
  228.             return [$context->getItemRounding(), $context->getTotalRounding()];
  229.         }
  230.         $criteria = new Criteria();
  231.         $criteria->setTitle('context-factory::cash-rounding');
  232.         $criteria->setLimit(1);
  233.         $criteria->addFilter(new EqualsFilter('currencyId'$context->getCurrencyId()));
  234.         $criteria->addFilter(new EqualsFilter('countryId'$shippingLocation->getCountry()->getId()));
  235.         /** @var CurrencyCountryRoundingEntity|null $countryConfig */
  236.         $countryConfig $this->currencyCountryRepository
  237.             ->search($criteria$context->getContext())
  238.             ->first();
  239.         if ($countryConfig) {
  240.             return [$countryConfig->getItemRounding(), $countryConfig->getTotalRounding()];
  241.         }
  242.         return [$context->getCurrency()->getItemRounding(), $context->getCurrency()->getTotalRounding()];
  243.     }
  244. }