getFlat example

$this->createTestData();

        $flowEntity = $this->flowRepository->search(new Criteria([$this->ids->get('flow_id')]), Context::createDefaultContext())->getEntities()->first();
        static::assertInstanceOf(FlowEntity::class$flowEntity);

        $payload = $flowEntity->getPayload();
        static::assertIsString($payload);
        $flow = unserialize($payload);
        static::assertInstanceOf(Flow::class$flow);
        static::assertInstanceOf(IfSequence::class$flow->getSequences()[0]);

        $flat = $flow->getFlat();
        static::assertInstanceOf(ActionSequence::class$flat[$this->ids->create('flow_sequence_id1')]);
        static::assertInstanceOf(IfSequence::class$flat[$this->ids->create('flow_sequence_id')]);

        $flow->jump($this->ids->create('flow_sequence_id1'));
        static::assertInstanceOf(ActionSequence::class$flow->getSequences()[0]);
    }

    private function createTestData(): void
    {
        $this->flowRepository->create([[
            'id' => $this->ids->create('flow_id'),
            
if (!$scope instanceof CheckoutRuleScope) {
            return false;
        }
        if ($scope instanceof LineItemScope) {
            return $this->container->match($scope);
        }

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

        foreach ($scope->getCart()->getLineItems()->getFlat() as $lineItem) {
            $context = new LineItemScope($lineItem$scope->getSalesChannelContext());
            $match = $this->container->match($context);
            if ($match) {
                return true;
            }
        }

        return false;
    }

    public function getConstraints(): array
    {
#[Package('checkout')] class ProductLineItemValidator implements CartValidatorInterface
{
    public function validate(Cart $cart, ErrorCollection $errors, SalesChannelContext $context): void
    {
        $behavior = $cart->getBehavior();
        if ($behavior !== null && $behavior->hasPermission(ProductCartProcessor::SKIP_PRODUCT_STOCK_VALIDATION)) {
            return;
        }

        $productLineItems = array_filter($cart->getLineItems()->getFlat()static fn (LineItem $lineItem) => $lineItem->getType() === LineItem::PRODUCT_LINE_ITEM_TYPE);

        $quantities = [];
        $refs = [];
        foreach ($productLineItems as $lineItem) {
            $productId = $lineItem->getReferencedId();
            if ($productId === null) {
                continue;
            }

            $quantities[$productId] = $lineItem->getQuantity() + ($quantities[$productId] ?? 0);

            
use Shopware\Core\Checkout\Cart\CartValidatorInterface;
use Shopware\Core\Checkout\Cart\Error\ErrorCollection;
use Shopware\Core\Checkout\Cart\Error\IncompleteLineItemError;
use Shopware\Core\Framework\Log\Package;
use Shopware\Core\System\SalesChannel\SalesChannelContext;

#[Package('checkout')] class LineItemValidator implements CartValidatorInterface
{
    public function validate(Cart $cart, ErrorCollection $errors, SalesChannelContext $context): void
    {
        foreach ($cart->getLineItems()->getFlat() as $lineItem) {
            if ($lineItem->getLabel() === null && $lineItem->getType() !== LineItem::CONTAINER_LINE_ITEM) {
                $errors->add(new IncompleteLineItemError($lineItem->getId(), 'label'));
                $cart->getLineItems()->removeElement($lineItem);
            }

            if ($lineItem->getPrice() === null) {
                $errors->add(new IncompleteLineItemError($lineItem->getId(), 'price'));
                $cart->getLineItems()->removeElement($lineItem);
            }
        }
    }
}
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 [
            
new LineItemCollection([
                        (new LineItem('A', 'test'))->setGood(true),
                        (new LineItem('B', 'test'))->setGood(true),
                    ])
                )
        );

        $cart->add(
            (new LineItem('flat', 'flat'))->setGood(true)
        );

        static::assertCount(4, $cart->getLineItems()->getFlat());
        static::assertCount(2, $cart->getLineItems());
    }

    /** * @throws CartException */
    public function testRemoveNonRemovableLineItemFromCart(): void
    {
        $cart = new Cart('test');

        $lineItem = new LineItem('A', 'test');
        
$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);
    }

    


    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;
        });
    }
}
return $this->elements[$identifier];
        }

        return null;
    }

    /** * @return LineItem[] */
    public function filterFlatByType(string $type): array
    {
        $lineItems = $this->getFlat();

        $filtered = [];
        foreach ($lineItems as $lineItem) {
            if ($lineItem->getType() === $type) {
                $filtered[] = $lineItem;
            }
        }

        return $filtered;
    }

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

        static::assertTrue($discountItem->hasPayloadValue('composition'), 'composition node is missing');

        /** @var array<int, mixed> $composition */
        $composition = $discountItem->getPayload()['composition'];

        static::assertEquals($productId1$composition[0]['id']);
        static::assertEquals(3, $composition[0]['quantity']);
        static::assertEquals(18, $composition[0]['discount']);

        static::assertEquals($productId2$composition[1]['id']);
        
$position->getLineItem()->setQuantityInformation(null);

                foreach ($position->getLineItem()->getChildren() as $lineItem) {
                    $lineItem->setDeliveryInformation(null);
                    $lineItem->setQuantityInformation(null);
                }
            }

            $delivery->getShippingMethod()->setPrices(new ShippingMethodPriceCollection());
        }

        foreach ($cart->getLineItems()->getFlat() as $lineItem) {
            $lineItem->setDeliveryInformation(null);
            $lineItem->setQuantityInformation(null);
        }

        $this->resetDataTimestamps($cart->getLineItems());
        foreach ($cart->getDeliveries() as $delivery) {
            $this->resetDataTimestamps($delivery->getPositions()->getLineItems());
        }
        $cart->setRuleIds([]);
        // The behaviour will be set during the process, therefore we remove it here         $cart->setBehavior(null);

        
$listener = $this->getMockBuilder(CallableClass::class)->getMock();
        $listener->expects(static::once())->method('__invoke');

        $this->addEventListener($dispatcher, CartBeforeSerializationEvent::class$listener);

        $connection = $this->createMock(Connection::class);
        $connection->expects(static::once())->method('fetchFirstColumn')->willReturn($allowed);

        $cleaner = new CartSerializationCleaner($connection$dispatcher);
        $cleaner->cleanupCart($cart);

        $items = $cart->getLineItems()->getFlat();
        foreach ($items as $item) {
            static::assertArrayHasKey($item->getId()$payloads);
            static::assertEquals($payloads[$item->getId()]$item->getPayload());
        }

        $delivery = $cart->getDeliveries()->first();
        $deliveryItems = $delivery !== null ? $delivery->getPositions()->getLineItems()->getFlat() : [];

        foreach ($deliveryItems as $item) {
            static::assertArrayHasKey($item->getId()$payloads);
            static::assertEquals($payloads[$item->getId()]$item->getPayload());
        }
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));
            }
static::assertNotNull($level1Item);
        static::assertCount(1, $level1Item->getChildren());

        $level2Item = $level1Item->getChildren()->first();
        static::assertNotNull($level2Item);
        static::assertCount(1, $level2Item->getChildren());

        $level3Item = $level2Item->getChildren()->first();
        static::assertNotNull($level3Item);
        static::assertEmpty($level3Item->getChildren());

        $allLineItems = $nestedCollection->getFlat();
        static::assertCount(3, $allLineItems);
        foreach ($allLineItems as $item) {
            static::assertNotEquals($noneExistingParent$item->getId());
        }
    }

    public function testTransformFlatToNestedReturnsEmptyCollectionOnEmptyInput(): void
    {
        $orderLineItemCollection = new OrderLineItemCollection();

        $nestedCollection = LineItemTransformer::transformFlatToNested($orderLineItemCollection);
        
Home | Imprint | This part of the site doesn't use cookies.