RuleCollection example

$builder = new PromotionItemBuilder();

        $discount = new PromotionDiscountEntity();
        $discount->setId('D5');
        $discount->setType(PromotionDiscountEntity::TYPE_ABSOLUTE);
        $discount->setValue(50);
        $discount->setConsiderAdvancedRules(true);
        $discount->setScope(PromotionDiscountEntity::SCOPE_CART);

        $currencyFactor = 0.3;

        $ruleCollection = new RuleCollection();
        $discount->setDiscountRules($ruleCollection);

        $item = $builder->buildDiscountLineItem('my-Code-123', $this->promotion, $discount, 'C1', $currencyFactor);

        $expected = [
            'promotionId' => 'PR-1',
            'discountId' => 'D5',
            'code' => 'my-Code-123',
            'discountType' => 'absolute',
            'value' => '50',
            'maxValue' => '',
            
/** * This test verifies that our extractor starts * with the sorting, then proceeds with rule matching and packagers. * This helps us to avoid any dependencies to rules inside sorters or packagers * * @group lineitemgroup */
    public function testRulesMatchingFirst(): void
    {
        $cart = $this->buildCart(1);

        $group = $this->buildGroup('FAKE-PACKAGER', 2, 'FAKE-SORTER', new RuleCollection());

        $this->integrationTestBuilder->findGroupPackages([$group]$cart$this->context);

        $countMatcher = $this->fakeTakeAllRuleMatcher->getSequenceCount();

        $countSorter = $this->fakeSorter->getSequenceCount();

        $countPackager = $this->fakeTakeAllPackager->getSequenceCount();

        // check if the matcher is called before the other objects         $isCalledFirst = ($countSorter < $countMatcher) && ($countMatcher < $countPackager);

        
/** * @internal */
class TestInternalFieldsAreFiltered extends SerializationFixture
{
    /** * @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;
    }

    
$activeRule = new RuleEntity();
        $activeRule->setId($ruleId);
        $activeRule->setName('Demo rule');
        $activeRule->setPriority(100);

        $ruleRepository = $this->createMock(EntityRepository::class);
        $ruleRepository
            ->method('search')
            ->willReturn(new EntitySearchResult(
                'rule',
                1,
                new RuleCollection([$activeRule]),
                null,
                new Criteria(),
                Context::createDefaultContext()
            ));

        $subscriber = new ActiveRulesDataCollectorSubscriber($ruleRepository);
        $subscriber->onContextResolved($event);
        $subscriber->collect(new Request()new Response());

        $data = $subscriber->getData();

        
$processor
            ->expects(static::exactly(3))
            ->method('process')
            ->with(static::isInstanceOf(Cart::class)$salesChannelContextstatic::isInstanceOf(CartBehavior::class))
            ->willReturn($calculatedCart);

        $ruleLoader = $this->createMock(RuleLoader::class);
        $ruleLoader
            ->expects(static::once())
            ->method('load')
            ->with($salesChannelContext->getContext())
            ->willReturn(new RuleCollection());

        $cartRuleLoader = new CartRuleLoader(
            $persister,
            $processor,
            new NullLogger(),
            $this->createMock(CacheInterface::class),
            $ruleLoader,
            $this->createMock(TaxDetector::class),
            $this->createMock(Connection::class),
            $factory,
        );

        
use Shopware\Core\Test\Stub\Rule\TrueRule;

/** * @covers \Shopware\Core\Framework\Rule\RuleCollection * * @internal */
class RuleCollectionTest extends TestCase
{
    public function testMetaCollecting(): void
    {
        $collection = new RuleCollection([
            new TrueRule(),
            new AndRule([
                new TrueRule(),
                new OrRule([
                    new TrueRule(),
                    new FalseRule(),
                ]),
            ]),
        ]);

        static::assertTrue($collection->has(FalseRule::class));
        

    public function testPackagerKeyId(): void
    {
        $group = new LineItemGroupDefinition('ID-1', 'COUNT', 2, 'PRICE_ASC', new RuleCollection());

        static::assertEquals('ID-1', $group->getId());
    }

    /** * This test verifies that our property is correctly * assigned and returned in its getter. * * @group lineitemgroup */
    public function testPackagerKeyProperty(): void
    {
public function testPreconditionRulePersonaRules(): void
    {
        $fakePersonaRule = new AndRule();

        $personaRuleEntity = new RuleEntity();
        $personaRuleEntity->setId('R1');
        $personaRuleEntity->setPayload($fakePersonaRule);

        $promotion = new PromotionEntity();
        $promotion->setCustomerRestriction(false);

        $promotion->setPersonaRules(new RuleCollection([$personaRuleEntity]));

        $expected = new AndRule(
            [
                new OrRule(
                    [$fakePersonaRule]
                ),
            ]
        );

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

    
$flow->setData(OrderAware::ORDER, $order);

        $scopeBuilder->method('build')->willReturn(
            new FlowRuleScope($ordernew Cart('test')$this->createMock(SalesChannelContext::class))
        );

        $rule = new OrderTagRule(Rule::OPERATOR_EQ, [$tagId]);
        $ruleEntity = new RuleEntity();
        $ruleEntity->setId($ruleId);
        $ruleEntity->setPayload($rule);
        $ruleEntity->setAreas([RuleAreas::FLOW_AREA]);
        $ruleLoader->method('load')->willReturn(new RuleCollection([$ruleEntity]));

        $flowExecutor = new FlowExecutor($eventDispatcher$appFlowActionProvider$ruleLoader$scopeBuilder[]);
        $flowExecutor->executeIf($ifSequence$flow);

        static::assertEquals($trueCaseSequence$flow->getFlowState()->currentSequence);
    }
}


    public function load(Context $context): RuleCollection
    {
        $criteria = new Criteria();
        $criteria->addSorting(new FieldSorting('priority', FieldSorting::DESCENDING));
        $criteria->addSorting(new FieldSorting('id'));
        $criteria->setLimit(500);
        $criteria->setTitle('cart-rule-loader::load-rules');

        $repositoryIterator = new RepositoryIterator($this->repository, $context$criteria);
        $rules = new RuleCollection();
        while (($result = $repositoryIterator->fetch()) !== null) {
            foreach ($result->getEntities() as $rule) {
                if (!$rule->isInvalid() && $rule->getPayload()) {
                    $rules->add($rule);
                }
            }
            if ($result->count() < 500) {
                break;
            }
        }

        
$ruleC = new RuleEntity();
        $ruleC->setId(Uuid::randomHex());
        $ruleC->setAreas(['c']);

        $ruleD = new RuleEntity();
        $ruleD->setId(Uuid::randomHex());

        $ruleE = new RuleEntity();
        $ruleE->setId(Uuid::randomHex());
        $ruleE->setAreas(['a', 'd']);

        $collection = new RuleCollection([$ruleA$ruleB$ruleC$ruleD$ruleE]);

        static::assertEquals([
            'a' => [$ruleA->getId()$ruleE->getId()],
            'b' => [$ruleA->getId()$ruleB->getId()],
            'c' => [$ruleB->getId()$ruleC->getId()],
            'd' => [$ruleE->getId()],
        ]$collection->getIdsByArea());
    }
}
/** * @param RuleEntity[] $rules */
    private function createSetGroup(string $packagerKey, float $value, string $sorterKey, array $rules): PromotionSetGroupEntity
    {
        $group = new PromotionSetGroupEntity();
        $group->setId(Uuid::randomBytes());

        $group->setPackagerKey($packagerKey);
        $group->setValue($value);
        $group->setSorterKey($sorterKey);
        $group->setSetGroupRules(new RuleCollection($rules));

        return $group;
    }

    private function createSetGroupWithRuleFixture(string $groupId, string $packagerKey, float $value, string $sorterKey, string $promotionId, string $ruleId, ContainerInterface $container): string
    {
        $context = $container->get(SalesChannelContextFactory::class)->create(Uuid::randomHex(), TestDefaults::SALES_CHANNEL);

        $repository = $container->get('promotion_setgroup.repository');

        $data = [
            
/** * This test verifies that we really search for items * in our hasFoundItems function. * If we have found groups, but no items in there, it should * also return FALSE. * * @group lineitemgroup */
    public function testHasItemsOnGroupWithNoResults(): void
    {
        $groupDefinition = new LineItemGroupDefinition('ID1', 'COUNT', 2, 'PRICE_ASC', new RuleCollection());

        $group = new LineItemGroup();

        $result = new LineItemGroupBuilderResult();
        $result->addGroup($groupDefinition$group);

        static::assertFalse($result->hasFoundItems());
    }

    /** * This test verifies that we get TRUE * if we have existing entries. * * @group lineitemgroup */
'',
                    $conversionContext->shouldIncludeOrderDate()
                );
            });

        $this->cartRuleLoader
            ->expects(static::once())
            ->method('loadByCart')
            ->willReturn(
                new RuleLoaderResult(
                    $cart,
                    new RuleCollection()
                )
            );

        $recalculationService = new RecalculationService(
            $entityRepository,
            $this->orderConverter,
            $this->createMock(CartService::class),
            $entityRepository,
            $entityRepository,
            $entityRepository,
            $this->createMock(Processor::class),
            
$this->context = Generator::createSalesChannelContext();
    }

    /** * @dataProvider lineItemProvider */
    public function testMatching(bool $withRules, bool $diffrentId, bool $expected): void
    {
        $lineItem = $this->createProductItem(50, 10);
        $lineItem->setReferencedId($lineItem->getId());

        $ruleCollection = new RuleCollection();

        if ($withRules === true) {
            $matchId = $diffrentId === true ? Uuid::randomHex() : $lineItem->getId();

            $ruleCollection->add($this->buildRuleEntity(
                $this->getProductsRule([$matchId])
            ));
        }

        $group = new LineItemGroupDefinition('test', 'COUNT', 1, 'PRICE_ASC', $ruleCollection);

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