LineItem example

public function testHasLineItemWithState(LineItemCollection $collection, array $expectedResults): void
    {
        foreach ($expectedResults as $state => $expected) {
            static::assertSame($expected$collection->hasLineItemWithState($state), 'Line item of state `' . $state . '` could not be found.');
        }
    }

    public static function lineItemStateProvider(): \Generator
    {
        yield 'collection has line item with state download and physical' => [
            new LineItemCollection([
                (new LineItem('A', 'test'))->setStates([State::IS_PHYSICAL]),
                (new LineItem('B', 'test'))->setStates([State::IS_DOWNLOAD]),
            ]),
            [State::IS_PHYSICAL => true, State::IS_DOWNLOAD => true],
        ];
        yield 'collection has line item with only state physical' => [
            new LineItemCollection([
                (new LineItem('A', 'test'))->setStates([State::IS_PHYSICAL]),
                (new LineItem('B', 'test'))->setStates([State::IS_PHYSICAL]),
            ]),
            [State::IS_PHYSICAL => true, State::IS_DOWNLOAD => false],
        ];
        
use Shopware\Core\Framework\Log\Package;
use Shopware\Core\Framework\Uuid\Uuid;

#[Package('checkout')] trait LineItemTestFixtureBehaviour
{
    /** * Create a simple product line item with the provided price. */
    private function createProductItem(float $netPrice, float $taxRate, ?float $listPriceNet = null): LineItem
    {
        $product = new LineItem(Uuid::randomBytes(), LineItem::PRODUCT_LINE_ITEM_TYPE);

        // allow quantity change         $product->setStackable(true);

        $taxValue = $netPrice * ($taxRate / 100.0);

        $grossPrice = $netPrice + $taxValue;

        $calculatedTaxes = new CalculatedTaxCollection();
        $calculatedTaxes->add(new CalculatedTax($taxValue$taxRate$taxValue));

        
yield 'test height/width/length: 1, 1, null' => [1, 1, null, 0];
    }

    private function getLineItem(
        float $weight = 10.0,
        int $quantity = 1,
        bool $freeDelivery = true,
        ?float $height = null,
        ?float $width = null,
        ?float $length = null
    ): LineItem {
        return (new LineItem(Uuid::randomHex(), 'product', null, $quantity))
            ->setPrice(new CalculatedPrice(0, 0, new CalculatedTaxCollection()new TaxRuleCollection()))
            ->setDeliveryInformation(
                new DeliveryInformation(
                    $quantity,
                    $weight,
                    $freeDelivery,
                    null,
                    null,
                    $height,
                    $width,
                    $length,
                )
static::assertSame('test', $lineItem->getReferencedId());
        static::assertSame(LineItem::PRODUCT_LINE_ITEM_TYPE, $lineItem->getType());
        static::assertSame(1, $lineItem->getQuantity());
        static::assertInstanceOf(QuantityPriceDefinition::class$lineItem->getPriceDefinition());
        static::assertSame(100.0, $lineItem->getPriceDefinition()->getPrice());
    }

    public function testUpdateDisabledStackable(): void
    {
        $id = Uuid::randomHex();
        $lineItem = new LineItem($id, LineItem::PRODUCT_LINE_ITEM_TYPE, Uuid::randomHex(), 1);
        $lineItem->setStackable(false);

        $cart = new Cart('test');
        $cart->add($lineItem);

        $this->expectException(CartException::class);

        $this->service->update($cart['id' => $id, 'quantity' => 2]$this->context);
    }

    public function testChangeQuantity(): void
    {
$context
            ->method('getTaxState')
            ->willReturn(CartPrice::TAX_STATE_FREE);

        $processor->process($cart$context);
    }

    private function createCart(): Cart
    {
        $cart = new Cart('test');

        $lineItem = new LineItem(
            $this->ids->get('line-item-1'),
            LineItem::PRODUCT_LINE_ITEM_TYPE,
            $this->ids->get('line-item-1'),
            1,
        );

        $taxes = new CalculatedTaxCollection([
            new CalculatedTax(
                19,
                19,
                100
            ),

#[Package('business-ops')] class LineItemRuleTest extends TestCase
{
    public function testRuleMatch(): void
    {
        $rule = (new LineItemRule())
            ->assign(['identifiers' => ['A']]);

        $context = $this->createMock(SalesChannelContext::class);

        $lineItem = new LineItem('A', 'product', 'A');

        static::assertTrue(
            $rule->match(new LineItemScope($lineItem$context))
        );

        $cart = new Cart('test');
        $cart->add($lineItem);

        static::assertTrue(
            $rule->match(new CartRuleScope($cart$context))
        );
    }


    public function testCheckoutRegister(): void
    {
        $context = Generator::createSalesChannelContext();
        $context->assign(['customer' => null]);
        $request = new Request();
        $request->attributes->set('_route', 'frontend.checkout.register.page');
        $dataBag = new RequestDataBag();
        $page = new CheckoutRegisterPage();
        $cart = new Cart(Uuid::randomHex());
        $cart->add(new LineItem('test', 'test'));

        $this->checkoutRegisterPageLoader->expects(static::once())
            ->method('load')
            ->with($request$context)
            ->willReturn($page);

        $this->cartService->expects(static::once())
            ->method('getCart')
            ->with($context->getToken()$context)
            ->willReturn($cart);

        
yield 'Test cover thumbnailRo cleanup without cover' => [
            self::coverCart('foo', null, true),
            null,
        ];
    }

    /** * @param array<string, mixed> $payload */
    private static function payloadItem(string $id, array $payload): LineItem
    {
        $item = new LineItem($id, 'foo');
        $item->setPayload($payload);

        $childItem = new LineItem($id . '-child', 'foo');
        $childItem->setPayload($payload);

        $item->addChild($childItem);

        return $item;
    }

    private static function coverItem(string $id, ?string $thumbnailString, bool $skipCover = false): LineItem
    {

        $url = EnvironmentHelper::getVariable('REDIS_URL');

        if (!$url) {
            static::markTestSkipped('No redis server configured');
        }

        $this->getContainer()->get(Connection::class)->executeStatement('DELETE FROM cart');

        $redisCart = new Cart(Uuid::randomHex());
        $redisCart->add(
            (new LineItem('A', 'test'))
                ->setPrice(new CalculatedPrice(0, 0, new CalculatedTaxCollection()new TaxRuleCollection()))
        );

        $context = $this->getSalesChannelContext($redisCart->getToken());

        $factory = new RedisConnectionFactory('test-prefix-');
        $redis = $factory->create((string) $url);
        static::assertInstanceOf(\Redis::class$redis);
        $redis->flushAll();

        $persister = new RedisCartPersister($redis$this->getContainer()->get('event_dispatcher')$this->getContainer()->get(CartSerializationCleaner::class), false, 90);
        


        $rule = new LineItemStockRule(Rule::OPERATOR_EQ, 5);

        static::assertFalse(
            $rule->match(new CartRuleScope($cartstatic::createMock(SalesChannelContext::class)))
        );
    }

    public function testMatchesIfNoDeliveryStatusIsSetAndRuleUsesNegativeOperatorIn6500(): void
    {
        $lineItem = new LineItem('test-id', LineItem::DISCOUNT_LINE_ITEM);

        static::assertNull($lineItem->getDeliveryInformation());

        $cart = new Cart('some-token');
        $cart->setLineItems(new LineItemCollection([$lineItem]));

        $lineItemScope = new LineItemScope($lineItemstatic::createMock(SalesChannelContext::class));
        $cartScope = new CartRuleScope($cartstatic::createMock(SalesChannelContext::class));

        static::assertFalse((new LineItemStockRule(Rule::OPERATOR_EQ, 5))->match($lineItemScope));
        static::assertFalse((new LineItemStockRule(Rule::OPERATOR_EQ, 5))->match($cartScope));

        
static::assertSame(
            $shouldMatch,
            $rule->match(new CartRuleScope($cart$context))
        );
    }

    public static function matchProvider(): \Generator
    {
        $ids = new IdsCollection();

        yield 'Id should not be used' => [
            new LineItem($ids->get('line-item-id'), LineItem::PRODUCT_LINE_ITEM_TYPE, null),
            new LineItemWithQuantityRule(Rule::OPERATOR_EQ, $ids->get('line-item-id'), 1),
            false,
        ];

        yield 'Reference id should match' => [
            new LineItem($ids->get('line-item-id'), LineItem::PRODUCT_LINE_ITEM_TYPE, $ids->get('reference-id')),
            new LineItemWithQuantityRule(Rule::OPERATOR_EQ, $ids->get('reference-id'), 1),
            true,
        ];

        yield 'Reference id should match with quantity' => [
            
static::assertArrayHasKey('foreignKeys', $encoded['extensions']);

        static::assertArrayHasKey('score', $encoded['extensions']['search']);
        static::assertArrayHasKey('exposedFk', $encoded['extensions']['foreignKeys']);
        static::assertArrayNotHasKey('notExposedFk', $encoded['extensions']['foreignKeys']);
    }

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

        $item = new LineItem('test', LineItem::PRODUCT_LINE_ITEM_TYPE, 'test');

        $item->setPayload(['foo' => 'bar', 'bar' => 'foo']['foo' => false, 'bar' => true]);

        $cart->add($item);

        $serializer = new Serializer([new StructNormalizer()][new JsonEncoder()]);

        $encoded = (new StructEncoder($this->createMock(DefinitionRegistryChain::class)$serializer))
            ->encode($cartnew ResponseFields(null));

        static::assertIsArray($encoded);
        
static::assertEquals(RuleConstraints::uuidOperators(false)$constraints['operator']);
    }

    /** * @dataProvider getMatchValues * * @param list<string> $identifiers * @param list<string> $itemOptionIds */
    public function testCartScopeMatching(bool $expected, array $itemOptionIds, array $identifiers, string $operator): void
    {
        $lineItem = new LineItem(Uuid::randomHex(), LineItem::PRODUCT_LINE_ITEM_TYPE, null, 1);
        $lineItem->setPayloadValue('optionIds', $itemOptionIds);
        $lineItems = new LineItemCollection([$lineItem]);

        $cart = new Cart(Uuid::randomHex());
        $cart->setLineItems($lineItems);

        $context = $this->createMock(SalesChannelContext::class);
        $scope = new CartRuleScope($cart$context);

        $this->rule->assign(['identifiers' => $identifiers, 'operator' => $operator]);

        


    /** * @param array<int, int> $creditPrices */
    private function generateCreditItems(Cart $cart, array $creditPrices): Cart
    {
        $lineItems = [];

        foreach ($creditPrices as $price) {
            $creditId = Uuid::randomHex();
            $creditLineItem = (new LineItem($creditId, LineItem::CREDIT_LINE_ITEM_TYPE, $creditId, 1))
                ->setLabel('credit' . $price)
                ->setPriceDefinition(new AbsolutePriceDefinition($price));

            $lineItems[] = $creditLineItem;
        }

        $cart->setRuleIds($this->salesChannelContext->getRuleIds());

        return $this->cartService->add($cart$lineItems$this->salesChannelContext);
    }

    
use Shopware\Core\Framework\Log\Package;
use Shopware\Core\Framework\Uuid\Uuid;

#[Package('business-ops')] trait CartRuleHelperTrait
{
    protected static function createLineItem(
        string $type = LineItem::PRODUCT_LINE_ITEM_TYPE,
        int $quantity = 1,
        ?string $referenceId = null
    ): LineItem {
        return new LineItem(Uuid::randomHex()$type$referenceId$quantity);
    }

    protected static function createLineItemWithDeliveryInfo(
        bool $freeDelivery,
        int $quantity = 1,
        ?float $weight = 50.0,
        ?float $height = null,
        ?float $width = null,
        ?float $length = null,
        int $stock = 9999
    ): LineItem {
        
Home | Imprint | This part of the site doesn't use cookies.