getLineItems example

public function match(RuleScope $scope): bool
    {
        if ($scope instanceof LineItemScope) {
            return $this->matchWidthDimension($scope->getLineItem());
        }

        if (!$scope instanceof CartRuleScope) {
            return false;
        }

        foreach ($scope->getCart()->getLineItems()->filterGoodsFlat() as $lineItem) {
            if ($this->matchWidthDimension($lineItem)) {
                return true;
            }
        }

        return false;
    }

    public function getConstraints(): array
    {
        $constraints = [
            
return false;
        }

        if ($scope instanceof LineItemScope) {
            return $this->matchesReleaseDate($scope->getLineItem()$ruleValue);
        }

        if (!$scope instanceof CartRuleScope) {
            return false;
        }

        foreach ($scope->getCart()->getLineItems()->filterGoodsFlat() as $lineItem) {
            if ($this->matchesReleaseDate($lineItem$ruleValue)) {
                return true;
            }
        }

        return false;
    }

    public function getConfig(): RuleConfig
    {
        return (new RuleConfig())
            
public function match(RuleScope $scope): bool
    {
        if ($scope instanceof LineItemScope) {
            return $this->lineItemMatches($scope->getLineItem());
        }

        if (!$scope instanceof CartRuleScope) {
            return false;
        }

        $promotionLineItems = $scope->getCart()->getLineItems()->filterFlatByType(LineItem::PROMOTION_LINE_ITEM_TYPE);
        $hasNoPromotionLineItems = \count($promotionLineItems) === 0;

        if ($hasNoPromotionLineItems) {
            return $this->operator === self::OPERATOR_NEQ;
        }

        foreach ($promotionLineItems as $lineItem) {
            if ($lineItem->getPayloadValue('promotionId') === null) {
                continue;
            }

            


    /** * @throws UnsupportedOperatorException */
    public function match(RuleScope $scope): bool
    {
        if (!$scope instanceof CartRuleScope) {
            return false;
        }

        $goods = new LineItemCollection($scope->getCart()->getLineItems()->filterGoodsFlat());
        $filter = $this->filter;
        if ($filter !== null) {
            $context = $scope->getSalesChannelContext();

            $goods = $goods->filter(static function DLineItem $lineItem) use ($filter$context) {
                $scope = new LineItemScope($lineItem$context);

                return $filter->match($scope);
            });
        }

        
/** * @internal * * @covers \Shopware\Core\Checkout\Cart\Cart */
class CartTest extends TestCase
{
    public function testEmptyCartHasNoGoods(): void
    {
        $cart = new Cart('test');
        static::assertCount(0, $cart->getLineItems()->filterGoods());
    }

    public function testCartWithLineItemsHasGoods(): void
    {
        $cart = new Cart('test');
        $cart->add(
            (new LineItem('A', 'test'))
                ->setGood(true)
                ->setStackable(true)
        );
        $cart->add(
            (


    public function calculate(Cart $cart, SalesChannelContext $context): Cart
    {
        return Profiler::trace('cart-calculation', function D) use ($cart$context) {
            // validate cart against the context rules             $cart = $this->cartRuleLoader
                ->loadByCart($context$cartnew CartBehavior($context->getPermissions()))
                ->getCart();

            $cart->markUnmodified();
            foreach ($cart->getLineItems()->getFlat() as $lineItem) {
                $lineItem->markUnmodified();
            }

            return $cart;
        });
    }
}
$cart = $this->cartService->getCart($this->context->getToken()$this->context);

        // create first product and add to cart         $cart = $this->addProduct($productId1, 5, $cart$this->cartService, $this->context);
        $cart = $this->addProduct($productId2, 3, $cart$this->cartService, $this->context);

        // create promotion and add to cart         $cart = $this->addPromotionCode($code$cart$this->cartService, $this->context);

        /** @var CalculatedPrice $discountPrice */
        $discountPrice = $cart->getLineItems()->getFlat()[2]->getPrice();

        /** @var CalculatedTax $tax1 */
        $tax1 = $discountPrice->getCalculatedTaxes()->getElements()[19]->getTax();

        $tax2 = $discountPrice->getCalculatedTaxes()->getElements()[7]->getTax();

        // our correct values are based on a distribution of 2 + 3 instead of 5 + 3         static::assertEquals(-24.4, $tax1);
        static::assertEquals(-13.49, $tax2);
    }

    
private readonly StateMachineRegistry $stateMachineRegistry
    ) {
    }

    /** * @throws ConstraintViolationException */
    public function createOrder(DataBag $data, SalesChannelContext $context): string
    {
        $cart = $this->cartService->getCart($context->getToken()$context);

        $this->validateOrderData($data$context$cart->getLineItems()->hasLineItemWithState(State::IS_DOWNLOAD));

        $this->validateCart($cart$context->getContext());

        return $this->cartService->order($cart$context$data->toRequestDataBag());
    }

    /** * @internal Should not be called from outside the core */
    public function orderStateTransition(
        string $orderId,
        


        $this->getContainer()->get(CartPersister::class)
            ->save($cart$this->getSalesChannelContext($cart->getToken()));

        $token = $this->getContainer()->get(Connection::class)
            ->fetchOne('SELECT token FROM cart WHERE token = :token', ['token' => $cart->getToken()]);

        static::assertNotEmpty($token);

        static::assertInstanceOf(CartSavedEvent::class$caughtEvent);
        static::assertCount(1, $caughtEvent->getCart()->getLineItems());
        $firstLineItem = $caughtEvent->getCart()->getLineItems()->first();
        static::assertInstanceOf(LineItem::class$firstLineItem);
        static::assertSame('test', $firstLineItem->getLabel());
    }

    public function testCartCanBeUnserialized(): void
    {
        $cart = unserialize((string) file_get_contents(__DIR__ . '/fixtures/cart.blob'));

        static::assertInstanceOf(Cart::class$cart);
    }

    


    public function testCalculateSimplePrice(): void
    {
        $cart = new Cart('test');

        $lineItem = (new LineItem('A', 'test'))
            ->setPriceDefinition(new QuantityPriceDefinition(100, new TaxRuleCollection([])));

        $cart->add($lineItem);

        $calculated = $this->calculator->calculate($cart->getLineItems()$this->context, new CartBehavior());

        static::assertCount(1, $calculated);
        static::assertInstanceOf(LineItem::class$calculated->get('A'));
        static::assertInstanceOf(CalculatedPrice::class$calculated->get('A')->getPrice());
        static::assertSame(100.0, $calculated->get('A')->getPrice()->getTotalPrice());
    }

    public function testCalculateQuantityPrice(): void
    {
        $cart = new Cart('test');

        
if ($conversionContext->shouldIncludeCustomer()) {
            $customer = $context->getCustomer();
            if ($customer === null) {
                throw CartException::customerNotLoggedIn();
            }

            $data['orderCustomer'] = CustomerTransformer::transform($customer);
        }

        $data['languageId'] = $context->getLanguageId();

        $convertedLineItems = LineItemTransformer::transformCollection($cart->getLineItems());
        $shippingAddresses = [];

        if ($conversionContext->shouldIncludeDeliveries()) {
            $shippingAddresses = AddressTransformer::transformCollection($cart->getDeliveries()->getAddresses(), true);
            $data['deliveries'] = DeliveryTransformer::transformCollection(
                $cart->getDeliveries(),
                $convertedLineItems,
                $this->initialStateIdLoader->get(OrderDeliveryStates::STATE_MACHINE),
                $context->getContext(),
                $shippingAddresses
            );
        }

    public function match(RuleScope $scope): bool
    {
        if ($scope instanceof LineItemScope) {
            return $this->lineItemMatches($scope->getLineItem());
        }

        if (!$scope instanceof CartRuleScope) {
            return false;
        }

        foreach ($scope->getCart()->getLineItems()->filterGoodsFlat() as $lineItem) {
            if ($this->lineItemMatches($lineItem)) {
                return true;
            }
        }

        return false;
    }

    public function getConstraints(): array
    {
        return [
            
return Profiler::trace('cart::process', function D) use ($original$context$behavior) {
            $cart = new Cart($original->getToken());
            $cart->setCustomerComment($original->getCustomerComment());
            $cart->setAffiliateCode($original->getAffiliateCode());
            $cart->setCampaignCode($original->getCampaignCode());
            $cart->setSource($original->getSource());
            $cart->setBehavior($behavior);
            $cart->addState(...$original->getStates());

            if ($behavior->hookAware()) {
                // reset modified state that apps always have the same entry state                 foreach ($original->getLineItems()->getFlat() as $item) {
                    $item->markUnModifiedByApp();
                }
            }

            // move data from previous calculation into new cart             $cart->setData($original->getData());

            $this->runProcessors($original$cart$context$behavior);

            if ($behavior->hookAware()) {
                $this->executor->execute(new CartHook($cart$context));
            }
public function match(RuleScope $scope): bool
    {
        if ($scope instanceof LineItemScope) {
            return $this->lineItemMatches($scope->getLineItem());
        }

        if (!$scope instanceof CartRuleScope) {
            return false;
        }

        foreach ($scope->getCart()->getLineItems()->getFlat() as $lineItem) {
            if ($this->lineItemMatches($lineItem)) {
                return true;
            }
        }

        return false;
    }

    public function getConstraints(): array
    {
        return [
            
public function __construct(private readonly AbsolutePriceCalculator $calculator)
    {
    }

    public function process(
        CartDataCollection $data,
        Cart $original,
        Cart $toCalculate,
        SalesChannelContext $context,
        CartBehavior $behavior
    ): void {
        $lineItems = $original->getLineItems()->filterType(LineItem::CREDIT_LINE_ITEM_TYPE);

        foreach ($lineItems as $lineItem) {
            $definition = $lineItem->getPriceDefinition();

            if (!$definition instanceof AbsolutePriceDefinition) {
                continue;
            }

            $lineItem->setPrice(
                $this->calculator->calculate(
                    $definition->getPrice(),
                    
Home | Imprint | This part of the site doesn't use cookies.