getCart example

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

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

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

        return false;
    }

    public function matchLineItem(LineItem $lineItem): bool
    {
        /** * @var list<string> $value */
return $this->wrapInSalesChannelApiRoute($salesChannelApiRequestfn (): Response => $this->kernel->handle($salesChannelApiRequest, HttpKernelInterface::SUB_REQUEST));
    }

    #[Route(path: '/api/_proxy-order/{salesChannelId}', name: 'api.proxy-order.create')]     public function proxyCreateOrder(string $salesChannelId, Request $request, Context $context, RequestDataBag $data): Response
    {
        $this->fetchSalesChannel($salesChannelId$context);

        $salesChannelContext = $this->fetchSalesChannelContext($salesChannelId$request$context);

        $cart = $this->cartService->getCart($salesChannelContext->getToken()$salesChannelContext);

        $order = $this->orderRoute->order($cart$salesChannelContext$data)->getOrder();

        $orderId = $order->getId();
        $userId = $context->getSource() instanceof AdminApiSource ? $context->getSource()->getUserId() : null;
        $userId = $userId ? Uuid::fromHexToBytes($userId) : null;

        $context->scope(Context::SYSTEM_SCOPE, function D) use ($orderId$userId): void {
            $this->connection->executeStatement(
                'UPDATE `order` SET `created_by_id` = :createdById WHERE `id` = :id',
                ['createdById' => $userId, 'id' => Uuid::fromHexToBytes($orderId)]
            );
// prepare promotion         $this->createTestFixtureProduct($productId1, 65, 19, $container$this->context);
        $this->createTestFixtureProduct($productId2, 30, 7, $container$this->context);

        // prepare a percentage promotion with 100% OFF         // with a set group of the 2 cheapest items.         $promotionBuilder = $this->createPromotionFixtureBuilder($container)
            ->addSetGroup('COUNT', 2, 'PRICE_ASC')
            ->setCode($code)
            ->addDiscount(PromotionDiscountEntity::SCOPE_SET, PromotionDiscountEntity::TYPE_PERCENTAGE, 100.0, false, null);
        $cart = $this->getCart($promotionBuilder$productId1$productId2$code);

        static::assertEquals(65.0, $cart->getPrice()->getPositionPrice(), 'Position Total Price is wrong');
        static::assertEquals(65.0, $cart->getPrice()->getTotalPrice(), 'Total Price is wrong');
        static::assertEquals(54.62, $cart->getPrice()->getNetPrice(), 'Net Price is wrong');
        static::assertEquals(10.38, $cart->getPrice()->getCalculatedTaxes()->getAmount(), 'Taxes are wrong');
    }

    /** * This test verifies that we give correct absolute discounts if the * set group consists of different line items and custom quantities. * We have a package of 2 of the cheapest items. * We only have 2 different products in our cart with total quantity 3 (1x and 2x). * Our cheapest 2 items are 1x the item with quantity 1 and then only 1x * the item of the products with quantity 2. * We give 50 EUR discount on that package, which means the customer has to * pay (product 1 + product 2 - 50) + product 2. * * @group promotions * * @throws CartException */
$productId2 = Uuid::randomHex();
        $promotionId = Uuid::randomHex();
        $code = 'BF19';

        // add a new sample product         $this->createTestFixtureProduct($productId1, 50, 19, $this->getContainer()$this->context);
        $this->createTestFixtureProduct($productId2, 100, 19, $this->getContainer()$this->context);

        // add a new promotion         $this->createTestFixtureAbsolutePromotion($promotionId$code, 30, $this->getContainer(), PromotionDiscountEntity::SCOPE_CART);

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

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

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

        // get discount line item         $discountItem = $cart->getLineItems()->getFlat()[2];

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

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

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

        return false;
    }

    public function getConstraints(): array
    {
        $constraints = [
            
public function match(RuleScope $scope): bool
    {
        if (!$scope instanceof CartRuleScope) {
            return false;
        }

        if ($this->volume === null) {
            throw new UnsupportedValueException(\gettype($this->volume), self::class);
        }

        return RuleComparison::numeric($this->calculateCartVolume($scope->getCart())$this->volume, $this->operator);
    }

    public function getConstraints(): array
    {
        return [
            'volume' => RuleConstraints::float(),
            'operator' => RuleConstraints::numericOperators(false),
        ];
    }

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

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

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

        return false;
    }

    public function getConstraints(): array
    {
        $constraints = [
            
$browser = $this->createCart(TestDefaults::SALES_CHANNEL);

        $this->addProduct($browser, TestDefaults::SALES_CHANNEL, $productId);

        // Save promotion to database         $this->createTestFixturePercentagePromotion(Uuid::randomHex()$promotionCode, 100, null, $this->getContainer());

        // Add promotion code to our cart (not existing in DB)         $this->addPromotionCodeByAPI($browser, TestDefaults::SALES_CHANNEL, $promotionCode);

        $cart = $this->getCart($browser, TestDefaults::SALES_CHANNEL);

        $this->updateLineItemQuantity($browser, TestDefaults::SALES_CHANNEL, $cart['lineItems'][0]['id'], 3);

        $cart = $this->getCart($browser, TestDefaults::SALES_CHANNEL);
        static::assertCount(2, $cart['lineItems']);
    }

    public function testSwitchCustomerWithoutSalesChannelId(): void
    {
        $salesChannelContextFactory = $this->getContainer()->get(SalesChannelContextFactory::class);
        $salesChannelContext = $salesChannelContextFactory->create(Uuid::randomHex(), TestDefaults::SALES_CHANNEL);
        
'%number%' => $this->htmlSanitizer->sanitize($number, null, true)]
                ));

                return $this->createActionResponse($request);
            }

            /** @var string $productId */
            $productId = array_shift($data);

            $product = $this->productLineItemFactory->create(['id' => $productId, 'referencedId' => $productId]$context);

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

            $cart = $this->cartService->add($cart$product$context);

            if (!$this->traceErrors($cart)) {
                $this->addFlash(self::SUCCESS, $this->trans('checkout.addToCartSuccess', ['%count%' => 1]));
            }

            return $this->createActionResponse($request);
        });
    }

    
public function __construct(
        private readonly CheckoutCartPage $page,
        SalesChannelContext $context
    ) {
        parent::__construct($context->getContext());
        $this->salesChannelContext = $context;
    }

    public function getName(): string
    {
        if ($this->getCart()->getSource()) {
            return self::HOOK_NAME . '-' . $this->getCart()->getSource();
        }

        return self::HOOK_NAME;
    }

    public function getPage(): CheckoutCartPage
    {
        return $this->page;
    }

    


        $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 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;
            }

            

    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 [
            
public function testRecalculateOrderWithTaxStatus(): void
    {
        $deliveryEntity = new OrderDeliveryEntity();
        $deliveryEntity->setId(Uuid::randomHex());
        $deliveryEntity->setStateId(Uuid::randomHex());

        $deliveries = new OrderDeliveryCollection([$deliveryEntity]);

        $orderEntity = $this->orderEntity();
        $orderEntity->setDeliveries($deliveries);
        $cart = $this->getCart();

        $entityRepository = $this->createMock(EntityRepository::class);
        $entityRepository->method('search')->willReturnOnConsecutiveCalls(
            new EntitySearchResult('order', 1, new OrderCollection([$orderEntity]), null, new Criteria()$this->salesChannelContext->getContext()),
        );

        $entityRepository
            ->expects(static::once())
            ->method('upsert')
            ->willReturnCallback(function Darray $data, Context $context) use ($orderEntity) {
                static::assertSame($data[0]['stateId']$orderEntity->getStateId());
                


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

        $promotions = new LineItemCollection($scope->getCart()->getLineItems()->filterFlatByType(LineItem::PROMOTION_LINE_ITEM_TYPE));
        $filter = $this->filter;
        if ($filter !== null) {
            $context = $scope->getSalesChannelContext();

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

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

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