vendor/shopware/core/Checkout/Cart/CartRuleLoader.php line 127

Open in your IDE?
  1. <?php declare(strict_types=1);
  2. namespace Shopware\Core\Checkout\Cart;
  3. use Doctrine\DBAL\Connection;
  4. use Psr\Log\LoggerInterface;
  5. use Shopware\Core\Checkout\Cart\Event\CartCreatedEvent;
  6. use Shopware\Core\Checkout\Cart\Exception\CartTokenNotFoundException;
  7. use Shopware\Core\Checkout\Cart\LineItem\LineItem;
  8. use Shopware\Core\Checkout\Cart\Price\Struct\CartPrice;
  9. use Shopware\Core\Checkout\Cart\Tax\TaxDetector;
  10. use Shopware\Core\Content\Rule\RuleCollection;
  11. use Shopware\Core\Defaults;
  12. use Shopware\Core\Framework\Context;
  13. use Shopware\Core\Framework\DataAbstractionLayer\Exception\EntityNotFoundException;
  14. use Shopware\Core\Framework\Util\FloatComparator;
  15. use Shopware\Core\Framework\Uuid\Uuid;
  16. use Shopware\Core\Profiling\Profiler;
  17. use Shopware\Core\System\Country\CountryDefinition;
  18. use Shopware\Core\System\Country\CountryEntity;
  19. use Shopware\Core\System\SalesChannel\SalesChannelContext;
  20. use Symfony\Contracts\Cache\CacheInterface;
  21. use Symfony\Contracts\EventDispatcher\EventDispatcherInterface;
  22. use Symfony\Contracts\Service\ResetInterface;
  23. class CartRuleLoader implements ResetInterface
  24. {
  25.     private const MAX_ITERATION 7;
  26.     private CartPersisterInterface $cartPersister;
  27.     private ?RuleCollection $rules null;
  28.     private Processor $processor;
  29.     private LoggerInterface $logger;
  30.     private CacheInterface $cache;
  31.     private AbstractRuleLoader $ruleLoader;
  32.     private TaxDetector $taxDetector;
  33.     private EventDispatcherInterface $dispatcher;
  34.     private Connection $connection;
  35.     private array $currencyFactor = [];
  36.     /**
  37.      * @internal
  38.      */
  39.     public function __construct(
  40.         CartPersisterInterface $cartPersister,
  41.         Processor $processor,
  42.         LoggerInterface $logger,
  43.         CacheInterface $cache,
  44.         AbstractRuleLoader $loader,
  45.         TaxDetector $taxDetector,
  46.         Connection $connection,
  47.         EventDispatcherInterface $dispatcher
  48.     ) {
  49.         $this->cartPersister $cartPersister;
  50.         $this->processor $processor;
  51.         $this->logger $logger;
  52.         $this->cache $cache;
  53.         $this->ruleLoader $loader;
  54.         $this->taxDetector $taxDetector;
  55.         $this->dispatcher $dispatcher;
  56.         $this->connection $connection;
  57.     }
  58.     public function loadByToken(SalesChannelContext $contextstring $cartToken): RuleLoaderResult
  59.     {
  60.         try {
  61.             $cart $this->cartPersister->load($cartToken$context);
  62.             return $this->load($context$cart, new CartBehavior($context->getPermissions()), false);
  63.         } catch (CartTokenNotFoundException $e) {
  64.             $cart = new Cart($context->getSalesChannel()->getTypeId(), $cartToken);
  65.             $this->dispatcher->dispatch(new CartCreatedEvent($cart));
  66.             return $this->load($context$cart, new CartBehavior($context->getPermissions()), true);
  67.         }
  68.     }
  69.     public function loadByCart(SalesChannelContext $contextCart $cartCartBehavior $behaviorContextbool $isNew false): RuleLoaderResult
  70.     {
  71.         return $this->load($context$cart$behaviorContext$isNew);
  72.     }
  73.     public function reset(): void
  74.     {
  75.         $this->rules null;
  76.     }
  77.     public function invalidate(): void
  78.     {
  79.         $this->reset();
  80.         $this->cache->delete(CachedRuleLoader::CACHE_KEY);
  81.     }
  82.     private function load(SalesChannelContext $contextCart $cartCartBehavior $behaviorContextbool $new): RuleLoaderResult
  83.     {
  84.         return Profiler::trace('cart-rule-loader', function () use ($context$cart$behaviorContext$new) {
  85.             $rules $this->loadRules($context->getContext());
  86.             // save all rules for later usage
  87.             $all $rules;
  88.             $ids $new $rules->getIds() : $cart->getRuleIds();
  89.             // update rules in current context
  90.             $context->setRuleIds($ids);
  91.             $iteration 1;
  92.             $timestamps $cart->getLineItems()->fmap(function (LineItem $lineItem) {
  93.                 if ($lineItem->getDataTimestamp() === null) {
  94.                     return null;
  95.                 }
  96.                 return $lineItem->getDataTimestamp()->format(Defaults::STORAGE_DATE_TIME_FORMAT);
  97.             });
  98.             // start first cart calculation to have all objects enriched
  99.             $cart $this->processor->process($cart$context$behaviorContext);
  100.             do {
  101.                 $compare $cart;
  102.                 if ($iteration self::MAX_ITERATION) {
  103.                     break;
  104.                 }
  105.                 // filter rules which matches to current scope
  106.                 $rules $rules->filterMatchingRules($cart$context);
  107.                 // update matching rules in context
  108.                 $context->setRuleIds($rules->getIds());
  109.                 // calculate cart again
  110.                 $cart $this->processor->process($cart$context$behaviorContext);
  111.                 // check if the cart changed, in this case we have to recalculate the cart again
  112.                 $recalculate $this->cartChanged($cart$compare);
  113.                 // check if rules changed for the last calculated cart, in this case we have to recalculate
  114.                 $ruleCompare $all->filterMatchingRules($cart$context);
  115.                 if (!$rules->equals($ruleCompare)) {
  116.                     $recalculate true;
  117.                     $rules $ruleCompare;
  118.                 }
  119.                 ++$iteration;
  120.             } while ($recalculate);
  121.             $cart $this->validateTaxFree($context$cart$behaviorContext);
  122.             $index 0;
  123.             foreach ($rules as $rule) {
  124.                 ++$index;
  125.                 $this->logger->info(
  126.                     sprintf('#%s Rule detection: %s with priority %s (id: %s)'$index$rule->getName(), $rule->getPriority(), $rule->getId())
  127.                 );
  128.             }
  129.             $context->setRuleIds($rules->getIds());
  130.             // save the cart if errors exist, so the errors get persisted
  131.             if ($cart->getErrors()->count() > || $this->updated($cart$timestamps)) {
  132.                 $this->cartPersister->save($cart$context);
  133.             }
  134.             return new RuleLoaderResult($cart$rules);
  135.         });
  136.     }
  137.     private function loadRules(Context $context): RuleCollection
  138.     {
  139.         if ($this->rules !== null) {
  140.             return $this->rules;
  141.         }
  142.         return $this->rules $this->ruleLoader->load($context);
  143.     }
  144.     private function cartChanged(Cart $previousCart $current): bool
  145.     {
  146.         $previousLineItems $previous->getLineItems();
  147.         $currentLineItems $current->getLineItems();
  148.         return $previousLineItems->count() !== $currentLineItems->count()
  149.             || $previous->getPrice()->getTotalPrice() !== $current->getPrice()->getTotalPrice()
  150.             || $previousLineItems->getKeys() !== $currentLineItems->getKeys()
  151.             || $previousLineItems->getTypes() !== $currentLineItems->getTypes()
  152.         ;
  153.     }
  154.     private function detectTaxType(SalesChannelContext $contextfloat $cartNetAmount 0): string
  155.     {
  156.         $currency $context->getCurrency();
  157.         $currencyTaxFreeAmount $currency->getTaxFreeFrom();
  158.         $isReachedCurrencyTaxFreeAmount $currencyTaxFreeAmount && $cartNetAmount >= $currencyTaxFreeAmount;
  159.         if ($isReachedCurrencyTaxFreeAmount) {
  160.             return CartPrice::TAX_STATE_FREE;
  161.         }
  162.         $country $context->getShippingLocation()->getCountry();
  163.         $isReachedCustomerTaxFreeAmount $country->getCustomerTax()->getEnabled() && $this->isReachedCountryTaxFreeAmount($context$country$cartNetAmount);
  164.         $isReachedCompanyTaxFreeAmount $this->taxDetector->isCompanyTaxFree($context$country) && $this->isReachedCountryTaxFreeAmount($context$country$cartNetAmountCountryDefinition::TYPE_COMPANY_TAX_FREE);
  165.         if ($isReachedCustomerTaxFreeAmount || $isReachedCompanyTaxFreeAmount) {
  166.             return CartPrice::TAX_STATE_FREE;
  167.         }
  168.         if ($this->taxDetector->useGross($context)) {
  169.             return CartPrice::TAX_STATE_GROSS;
  170.         }
  171.         return CartPrice::TAX_STATE_NET;
  172.     }
  173.     /**
  174.      * @param array<string, string> $timestamps
  175.      */
  176.     private function updated(Cart $cart, array $timestamps): bool
  177.     {
  178.         foreach ($cart->getLineItems() as $lineItem) {
  179.             if (!isset($timestamps[$lineItem->getId()])) {
  180.                 return true;
  181.             }
  182.             $original $timestamps[$lineItem->getId()];
  183.             $timestamp $lineItem->getDataTimestamp() !== null $lineItem->getDataTimestamp()->format(Defaults::STORAGE_DATE_TIME_FORMAT) : null;
  184.             if ($original !== $timestamp) {
  185.                 return true;
  186.             }
  187.         }
  188.         return \count($timestamps) !== $cart->getLineItems()->count();
  189.     }
  190.     private function isReachedCountryTaxFreeAmount(
  191.         SalesChannelContext $context,
  192.         CountryEntity $country,
  193.         float $cartNetAmount 0,
  194.         string $taxFreeType CountryDefinition::TYPE_CUSTOMER_TAX_FREE
  195.     ): bool {
  196.         $countryTaxFreeLimit $taxFreeType === CountryDefinition::TYPE_CUSTOMER_TAX_FREE $country->getCustomerTax() : $country->getCompanyTax();
  197.         if (!$countryTaxFreeLimit->getEnabled()) {
  198.             return false;
  199.         }
  200.         $countryTaxFreeLimitAmount $countryTaxFreeLimit->getAmount() / $this->fetchCurrencyFactor($countryTaxFreeLimit->getCurrencyId(), $context);
  201.         $currency $context->getCurrency();
  202.         $cartNetAmount /= $this->fetchCurrencyFactor($currency->getId(), $context);
  203.         // currency taxFreeAmount === 0.0 mean currency taxFreeFrom is disabled
  204.         return $currency->getTaxFreeFrom() === 0.0 && FloatComparator::greaterThanOrEquals($cartNetAmount$countryTaxFreeLimitAmount);
  205.     }
  206.     private function fetchCurrencyFactor(string $currencyIdSalesChannelContext $context): float
  207.     {
  208.         if ($currencyId === Defaults::CURRENCY) {
  209.             return 1;
  210.         }
  211.         $currency $context->getCurrency();
  212.         if ($currencyId === $currency->getId()) {
  213.             return $currency->getFactor();
  214.         }
  215.         if (\array_key_exists($currencyId$this->currencyFactor)) {
  216.             return $this->currencyFactor[$currencyId];
  217.         }
  218.         $currencyFactor $this->connection->fetchOne(
  219.             'SELECT `factor` FROM `currency` WHERE `id` = :currencyId',
  220.             ['currencyId' => Uuid::fromHexToBytes($currencyId)]
  221.         );
  222.         if (!$currencyFactor) {
  223.             throw new EntityNotFoundException('currency'$currencyId);
  224.         }
  225.         return $this->currencyFactor[$currencyId] = (float) $currencyFactor;
  226.     }
  227.     private function validateTaxFree(SalesChannelContext $contextCart $cartCartBehavior $behaviorContext): Cart
  228.     {
  229.         $totalCartNetAmount $cart->getPrice()->getPositionPrice();
  230.         if ($context->getTaxState() === CartPrice::TAX_STATE_GROSS) {
  231.             $totalCartNetAmount $totalCartNetAmount $cart->getLineItems()->getPrices()->getCalculatedTaxes()->getAmount();
  232.         }
  233.         $taxState $this->detectTaxType($context$totalCartNetAmount);
  234.         $previous $context->getTaxState();
  235.         if ($taxState === $previous) {
  236.             return $cart;
  237.         }
  238.         $context->setTaxState($taxState);
  239.         $cart->setData(null);
  240.         $cart $this->processor->process($cart$context$behaviorContext);
  241.         if ($previous !== CartPrice::TAX_STATE_FREE) {
  242.             $context->setTaxState($previous);
  243.         }
  244.         return $cart;
  245.     }
  246. }