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

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