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

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