CartBehavior example

yield 'Discount product price' => [
            'discount-product-price',
            [
                'p1' => new ExpectedPrice(90, 90),
            ],
        ];
    }

    private function createCart(): Cart
    {
        $cart = new Cart('test');
        $cart->setBehavior(new CartBehavior());
        $cart->addState('default-state');

        return $cart;
    }

    /** * @param array<string, ExpectedPrice|null> $expectations */
    private function assertItems(ItemsFacade|CartFacade|LineItemCollection $scope, array $expectations): void
    {
        foreach ($expectations as $key => $expected) {
            


    private function buildDeliveries(LineItemCollection $lineItems, SalesChannelContext $context): DeliveryCollection
    {
        $data = new CartDataCollection();
        $data->set(DeliveryProcessor::buildKey($context->getShippingMethod()->getId())$context->getShippingMethod());

        $cart = new Cart('test');
        $cart->setLineItems($lineItems);

        return $this->getContainer()->get(DeliveryBuilder::class)
            ->build($cart$data$contextnew CartBehavior());
    }

    private function createLineItem(DeliveryInformation $deliveryInformation, CalculatedPrice $calculatedPrice): LineItem
    {
        $lineItem = new LineItem(Uuid::randomHex(), 'product');
        $lineItem->setDeliveryInformation($deliveryInformation);
        $lineItem->setPrice($calculatedPrice);

        return $lineItem;
    }
}
$this->scopes = [];
    }

    public function build(OrderEntity $order, Context $context): FlowRuleScope
    {
        if (\array_key_exists($order->getId()$this->scopes)) {
            return $this->scopes[$order->getId()];
        }

        $context = $this->orderConverter->assembleSalesChannelContext($order$context);
        $cart = $this->orderConverter->convertToCart($order$context->getContext());
        $behavior = new CartBehavior($context->getPermissions());

        foreach ($this->collectors as $collector) {
            $collector->collect($cart->getData()$cart$context$behavior);
        }

        $cart->setDeliveries(
            $this->deliveryBuilder->build($cart$cart->getData()$context$behavior)
        );

        return $this->scopes[$order->getId()] = new FlowRuleScope($order$cart$context);
    }
}
class CartCalculator
{
    public function __construct(private readonly CartRuleLoader $cartRuleLoader)
    {
    }

    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;
        });
    }
}
$salesChannelContext->setItemRounding($order->getItemRounding());
        }

        if ($order->getTotalRounding() !== null) {
            $salesChannelContext->setTotalRounding($order->getTotalRounding());
        }

        $cart = $this->orderConverter->convertToCart($order$salesChannelContext->getContext());
        $this->cartRuleLoader->loadByCart(
            $salesChannelContext,
            $cart,
            new CartBehavior($salesChannelContext->getPermissions()),
            true
        );

        return $salesChannelContext;
    }

    /** * @param array<string> $overrideOptions * * @throws Exception */
    
$originalCart = new Cart('original');
        $calculatedCart = new Cart('calculated');

        $lineItem = new LineItem('test', LineItem::PRODUCT_LINE_ITEM_TYPE);
        $lineItem->setDeliveryInformation(new DeliveryInformation(5, 0, false));
        $lineItem->setPrice(new CalculatedPrice(5.0, 5.0, new CalculatedTaxCollection([
            new CalculatedTax(5, 19, 5),
        ])new TaxRuleCollection()));

        $calculatedCart->setLineItems(new LineItemCollection([$lineItem]));

        $cartBehavior = new CartBehavior();

        static::assertCount(0, $calculatedCart->getDeliveries());

        $deliveryProcessor->process($cartDataCollection$originalCart$calculatedCart$this->salesChannelContext, $cartBehavior);

        // Deliveries were built         static::assertCount(1, $calculatedCart->getDeliveries());

        // Price was recalculated         static::assertNotNull($calculatedCart->getDeliveries()->first());
        static::assertSame(5.0, $calculatedCart->getDeliveries()->first()->getShippingCosts()->getTotalPrice());

        
$context = $this->salesChannelContextFactory->create(
            Uuid::randomHex(),
            TestDefaults::SALES_CHANNEL,
            [
                SalesChannelContextService::CUSTOMER_ID => $customerId,
            ]
        );

        $this->getContainer()->get(CartRuleLoader::class)->loadByToken($context$context->getToken());

        $cart = $this->processor->process($cart$contextnew CartBehavior());

        $id = $this->orderPersister->persist($cart$context);

        $count = $this->getContainer()->get(Connection::class)->fetchAllAssociative('SELECT * FROM `order` WHERE id = :id', ['id' => Uuid::fromHexToBytes($id)]);
        static::assertCount(1, $count);

        $this->orderRepository->delete([
            ['id' => $id],
        ], Context::createDefaultContext());

        $count = $this->getContainer()->get(Connection::class)->fetchAllAssociative('SELECT * FROM `order` WHERE id = :id', ['id' => Uuid::fromHexToBytes($id)]);
        
$product1 = $cart->get($parentProductId);
        $product2 = $cart->get($childProductId);

        static::assertNotNull($product1);
        static::assertNotNull($product2);

        $product1->getChildren()->add($product2);
        $cart->remove($childProductId);

        $cart = $this->getContainer()->get(Processor::class)
            ->process($cart$this->salesChannelContext, new CartBehavior());

        $orderId = $this->persistCart($cart)['orderId'];

        $deliveryCriteria = new Criteria();
        $deliveryCriteria->addAssociation('positions');

        $criteria = (new Criteria([$orderId]))
            ->addAssociation('lineItems')
            ->addAssociation('transactions')
            ->addAssociation('deliveries.shippingMethod')
            ->addAssociation('deliveries.positions.orderLineItem')
            
'salesChannelId' => TestDefaults::SALES_CHANNEL, 'visibility' => ProductVisibilityDefinition::VISIBILITY_ALL],
                ],
            ];

            $cart->add($factory->create(['id' => $id, 'referencedId' => $id]$this->salesChannelContext));
            $this->addTaxDataToSalesChannel($this->salesChannelContext, end($products)['tax']);
        }

        $this->getContainer()->get('product.repository')
            ->create($products, Context::createDefaultContext());

        $cart = $this->getContainer()->get(Processor::class)->process($cart$this->salesChannelContext, new CartBehavior());

        return $cart;
    }

    private function persistCart(Cart $cart): string
    {
        $cart = $this->getContainer()->get(CartService::class)->recalculate($cart$this->salesChannelContext);
        $orderId = $this->getContainer()->get(OrderPersister::class)->persist($cart$this->salesChannelContext);

        return $orderId;
    }

    
$latestDeliveryDate = $deliveryDate->getLatest();

        static::assertSame(
            $latestDeliveryDate->format(Defaults::STORAGE_DATE_TIME_FORMAT),
            $earliestDeliveryDate->format(Defaults::STORAGE_DATE_TIME_FORMAT)
        );
    }

    private function getDeliveries(Cart $cart): DeliveryCollection
    {
        $data = new CartDataCollection();
        $cartBehaviour = new CartBehavior();

        $this->processor->collect($data$cart$this->context, $cartBehaviour);

        return $this->builder->build($cart$data$this->context, $cartBehaviour);
    }

    private function createCart(bool $withoutLineItems = false): Cart
    {
        $cart = new Cart('test');
        if ($withoutLineItems) {
            return $cart;
        }
public function testSaveWithMissingLabel(): void
    {
        $cart = new Cart('a-b-c');
        $cart->add(
            (new LineItem('test', LineItem::CREDIT_LINE_ITEM_TYPE))
                ->setPriceDefinition(new AbsolutePriceDefinition(1))
        );

        $context = $this->getContainer()->get(SalesChannelContextFactory::class)
            ->create(Uuid::randomHex(), TestDefaults::SALES_CHANNEL);

        $processedCart = $this->cartProcessor->process($cart$contextnew CartBehavior());

        $exception = null;

        try {
            $this->orderPersister->persist($processedCart$context);
        } catch (CartException $exception) {
        }

        static::assertInstanceOf(CartException::class$exception);
        static::assertStringContainsString('Line item "test" incomplete. Property "label" missing.', $exception->getMessage());
    }

    

        $address = $this->orderAddressRepository->search(new Criteria([$orderAddressId])$context)->get($orderAddressId);
        if (!$address) {
            throw CartException::addressNotFound($orderAddressId);
        }

        $this->checkVersion($address);
    }

    private function recalculateCart(Cart $cart, SalesChannelContext $context): Cart
    {
        $behavior = new CartBehavior($context->getPermissions(), true, true);

        // all prices are now prepared for calculation - starts the cart calculation         $cart = $this->processor->process($cart$context$behavior);

        // validate cart against the context rules         $validated = $this->cartRuleLoader->loadByCart($context$cart$behavior);

        $cart = $validated->getCart();

        return $cart;
    }
}
$builder
                ->create(['id' => 'product-2', 'referencedId' => 'product-2']$salesChannelContext)
                ->setReferencedId('product-1')
                ->setQuantityInformation(
                    (new QuantityInformation())
                        ->setMinPurchase(1)
                        ->setMaxPurchase(1)
                        ->setPurchaseSteps(1)
                )
        );

        $cart->setBehavior(new CartBehavior([
            ProductCartProcessor::SKIP_PRODUCT_STOCK_VALIDATION => true,
        ]));

        static::assertCount(0, $cart->getErrors());

        $validator = new ProductLineItemValidator();
        $validator->validate($cart$cart->getErrors()$salesChannelContext);

        static::assertCount(0, $cart->getErrors());
    }

    
$context = $this->getContainer()->get(SalesChannelContextFactory::class)
            ->create(Uuid::randomHex(), TestDefaults::SALES_CHANNEL);

        $cart = new Cart('test');
        $cart->setLineItems(new LineItemCollection($items));

        $new = new Cart('after');
        $new->setLineItems(
            (new LineItemCollection($items))->filter(fn (LineItem $item) => $item->getType() !== LineItem::DISCOUNT_LINE_ITEM)
        );

        $processor->process(new CartDataCollection()$cart$new$contextnew CartBehavior());

        if ($expected === null) {
            static::assertFalse($new->has(self::DISCOUNT_ID));

            return;
        }

        static::assertTrue($new->has(self::DISCOUNT_ID));

        $item = $new->get(self::DISCOUNT_ID);
        static::assertInstanceOf(LineItem::class$item);
        
'salesChannelId' => TestDefaults::SALES_CHANNEL, 'visibility' => ProductVisibilityDefinition::VISIBILITY_ALL],
                ],
            ];

            $cart->add($factory->create(['id' => $id, 'referencedId' => $id]$this->salesChannelContext));
            $this->addTaxDataToSalesChannel($this->salesChannelContext, end($products)['tax']);
        }

        $this->getContainer()->get('product.repository')
            ->create($products, Context::createDefaultContext());

        $cart = $this->getContainer()->get(Processor::class)->process($cart$this->salesChannelContext, new CartBehavior());

        return $cart;
    }

    private function persistCart(Cart $cart): string
    {
        $cart = $this->getContainer()->get(CartService::class)->recalculate($cart$this->salesChannelContext);

        return $this->getContainer()->get(OrderPersister::class)->persist($cart$this->salesChannelContext);
    }

    
Home | Imprint | This part of the site doesn't use cookies.