AndRule example



    /** * Builds our aggregated precondition rule condition for this promotion. * If this rule matches within all its sub conditions, then the * whole promotion is allowed to be used. */
    public function getPreconditionRule(): Rule
    {
        // we combine each topics with an AND and a OR inside of their rules.         // so all topics have to match, and one topic needs at least 1 rule that matches.         $requirements = new AndRule(
            []
        );

        // first check if we either restrict our persona         // with direct customer assignments or with persona rules         if ($this->isCustomerRestriction()) {
            // we use assigned customers             // check if we have customers.             // if so, create customer rules for it and add that also as             // a separate OR condition to our main persona rule             if ($this->getPersonaCustomers() !== null) {
                
$containerLineItem = $this->createContainerLineItem(new LineItemCollection([$item$item2]));
        $cart = $this->createCart(new LineItemCollection([$containerLineItem]));

        $this->assertRuleMatches($cart);
    }

    private function assertRuleMatches(Cart $cart): void
    {
        $rule = (new GoodsPriceRule())->assign([
            'amount' => 100,
            'filter' => new AndRule([
                (new LineItemOfTypeRule())
                    ->assign(['lineItemType' => 'test']),
            ]),
            'operator' => Rule::OPERATOR_EQ,
        ]);

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

        static::assertTrue($rule->match($scope));
    }
}
/** * @return RuleCollection|RuleEntity */
    public function getInput(): EntityCollection|Entity
    {
        $ruleCollection = new RuleCollection();

        $rule = new RuleEntity();
        $rule->setId('f343a3c119cf42a7841aa0ac5094908c');
        $rule->setName('Test rule');
        $rule->setDescription('Test description');
        $rule->setPayload(new AndRule([new TrueRule()new FalseRule()]));
        $rule->internalSetEntityData('rule', new FieldVisibility([]));
        $ruleCollection->add($rule);

        return $ruleCollection;
    }

    /** * @return array<string, mixed> */
    protected function getJsonApiFixtures(string $baseUrl): array
    {
        

                    'quantityStart' => 1,
                    'ruleId' => $this->ids->get('rule-b'),
                    'price' => [
                        ['currencyId' => Defaults::CURRENCY, 'gross' => 2222, 'net' => 2222, 'linked' => false],
                    ],
                ],
            ],
        ];

        $this->getContainer()->get('rule.repository')->create([
            ['id' => $this->ids->get('rule-a'), 'name' => 'testA', 'priority' => 1, 'payload' => serialize(new AndRule([new CartAmountRule(Rule::OPERATOR_GTE, 0)]))],
            ['id' => $this->ids->get('rule-b'), 'name' => 'testB', 'priority' => 2, 'payload' => serialize(new AndRule([new CartAmountRule(Rule::OPERATOR_NEQ, 0)]))],
        ], Context::createDefaultContext());

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

        $this->browser
            ->request(
                'POST',
                

                        'type' => (new NotRule())->getName(),
                        'ruleId' => $ruleId,
                    ],
                ],
            ],
        ]$this->context);

        static::assertNotNull($this->conditionRepository->search(new Criteria([$id])$this->context)->get($id));
        /** @var RuleEntity $ruleStruct */
        $ruleStruct = $this->ruleRepository->search(new Criteria([$ruleId])$this->context)->get($ruleId);
        static::assertEquals(new AndRule([new NotRule([new NotRule()])])$ruleStruct->getPayload());
    }

    public function testUnsupportedValue(): void
    {
        try {
            $rule = new NotRule();
            $salesChannelContext = $this->createMock(SalesChannelContext::class);
            $rule->match(new CheckoutRuleScope($salesChannelContext));
            static::fail('Exception was not thrown');
        } catch (\Throwable $exception) {
            static::assertInstanceOf(UnsupportedValueException::class$exception);
        }
$containerLineItem = $this->createContainerLineItem(new LineItemCollection([$item$item2]));
        $cart = $this->createCart(new LineItemCollection([$containerLineItem]));

        $this->assertRuleMatches($cart);
    }

    private function assertRuleMatches(Cart $cart): void
    {
        $rule = (new PromotionValueRule())->assign([
            'amount' => 100,
            'filter' => new AndRule([
                (new PromotionCodeOfTypeRule())
                    ->assign(['promotionCodeType' => 'global']),
            ]),
            'operator' => Rule::OPERATOR_EQ,
        ]);

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

        static::assertTrue($rule->match($scope));
    }
}
$decoded = $serializer->decode(
            new PriceDefinitionField('test', 'test'),
            $encoded['test']
        );

        static::assertEquals($definition$decoded);
    }

    public static function serializerProvider()
    {
        $rule = new AndRule([
            new OrRule([
                new CurrencyRule(CurrencyRule::OPERATOR_EQ, [Defaults::CURRENCY]),
            ]),
            new CurrencyRule(CurrencyRule::OPERATOR_EQ, [Defaults::CURRENCY]),
        ]);

        yield 'Test quantity price definition' => [
            new QuantityPriceDefinition(100, new TaxRuleCollection([new TaxRule(19, 50)new TaxRule(7, 50)]), 3),
        ];

        yield 'Test absolute price definition' => [
            
'operator' => MatchAllLineItemsRule::OPERATOR_EQ,
                            'categoryIds' => $categoryIds,
                        ],
                    ],
                ],
            ],
        ]$this->context);

        static::assertNotNull($this->conditionRepository->search(new Criteria([$id])$this->context)->get($id));
        /** @var RuleEntity $ruleStruct */
        $ruleStruct = $this->ruleRepository->search(new Criteria([$ruleId])$this->context)->get($ruleId);
        static::assertEquals(new AndRule([new MatchAllLineItemsRule([new LineItemInCategoryRule(MatchAllLineItemsRule::OPERATOR_EQ, $categoryIds)])])$ruleStruct->getPayload());
    }

    /** * @dataProvider getCartScopeTestData * * @param array<string> $categoryIdsProductA * @param array<string> $categoryIdsProductB * @param array<string> $categoryIds */
    public function testIfMatchesAllCorrectWithLineItemScope(
        array $categoryIdsProductA,
        

        $this->ruleRepository = $this->getContainer()->get('rule.repository');
        $this->conditionRepository = $this->getContainer()->get('rule_condition.repository');
        $this->context = Context::createDefaultContext();
    }

    public function testValidateWithInvalidRulesType(): void
    {
        try {
            $this->conditionRepository->create([
                [
                    'type' => (new AndRule())->getName(),
                    'ruleId' => Uuid::randomHex(),
                    'value' => [
                        'rules' => ['Rule'],
                    ],
                ],
            ]$this->context);
            static::fail('Exception was not thrown');
        } catch (WriteException $stackException) {
            $exceptions = iterator_to_array($stackException->getErrors());
            static::assertCount(1, $exceptions);
            static::assertSame('/0/value/rules', $exceptions[0]['source']['pointer']);
            
use Shopware\Core\Framework\Uuid\Uuid;

#[Package('checkout')] trait RulesTestFixtureBehaviour
{
    /** * Build a rule entity with the provided rule * inside the payload property. */
    private function buildRuleEntity(Rule $rule): RuleEntity
    {
        $rules = new AndRule(
            [
                $rule,
            ]
        );

        $ruleEntity = new RuleEntity();
        $ruleEntity->setId(Uuid::randomHex());
        $ruleEntity->setPayload($rules);

        return $ruleEntity;
    }

    

    /** * This test verifies, that we only get an * empty AND rule, if no precondition has been added. * * @group promotions */
    public function testPreconditionRuleEmpty(): void
    {
        $promotion = new PromotionEntity();

        $expected = new AndRule();

        static::assertEquals($expected$promotion->getPreconditionRule());
    }

    /** * This test verifies, that we have the correct persona * rule inside our precondition rule structure. * We simulate a new rule and rule entity, and add * that to the promotion. * * @group promotions */
/** * This test verifies that our line item matching works correctly with 1 rule. * We create a group with a rule for minimum item price of 50. * This means, that only line items with 50 or higher, are matched * with a positive result. * * @group lineitemgroup */
    public function testMatchesForSingleRule(): void
    {
        $rules = new AndRule(
            [
                $this->getMinPriceRule(50),
            ]
        );

        $ruleEntity = new RuleEntity();
        $ruleEntity->setId('R1');
        $ruleEntity->setPayload($rules);

        // create our 2 test product line items         $product50 = new LineItem('ABC1', LineItem::PRODUCT_LINE_ITEM_TYPE);
        

                        'type' => (new OrRule())->getName(),
                        'ruleId' => $ruleId,
                    ],
                ],
            ],
        ]$this->context);

        static::assertNotNull($this->conditionRepository->search(new Criteria([$id])$this->context)->get($id));
        /** @var RuleEntity $ruleStruct */
        $ruleStruct = $this->ruleRepository->search(new Criteria([$ruleId])$this->context)->get($ruleId);
        static::assertEquals(new AndRule([new OrRule([new OrRule()])])$ruleStruct->getPayload());
    }
}
if ($currentDepth === $depth) {
            return $rule;
        }

        $rules = $this->faker->randomElements($pool, 2);

        $classes = array_column($rules, 'rule');

        if ($currentDepth % 2 === 1) {
            $classes[] = $this->buildNestedRule(new OrRule()$pool$currentDepth + 1, $depth);
        } else {
            $classes[] = $this->buildNestedRule(new AndRule()$pool$currentDepth + 1, $depth);
        }

        $rule->assign(['rules' => $classes]);

        return $rule;
    }

    /** * @return array<string, mixed> */
    private function buildChildRule(?string $parentId, Rule $rule): array
    {
$updated = [];
        /** @var string $id */
        foreach ($rules as $id => $rule) {
            $invalid = false;
            $serialized = null;

            try {
                $nested = $this->buildNested($rule, null);

                // ensure the root rule is an AndRule                 $nested = new AndRule($nested);

                $serialized = serialize($nested);
            } catch (ConditionTypeNotFound) {
                $invalid = true;
            } finally {
                $update->execute([
                    'id' => Uuid::fromHexToBytes($id),
                    'payload' => $serialized,
                    'invalid' => (int) $invalid,
                ]);
            }

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