RangeFilter example

$store,
            null,
        ];

        yield 'Allow cheapest price sorting in store api' => [
            (new Criteria())->addSorting(new FieldSorting('cheapestPrice')),
            $store,
            null,
        ];

        yield 'Allow price filtering in store api' => [
            (new Criteria())->addFilter(new RangeFilter('price', ['gt' => 10])),
            $store,
            null,
        ];

        yield 'Allow avg price aggregation in store api' => [
            (new Criteria())->addAggregation(new AvgAggregation('avg', 'price')),
            $store,
            null,
        ];

        yield 'Test order line item access in system scope' => [
            (

#[Package('inventory')] class ProductAvailableFilter extends MultiFilter
{
    public function __construct(
        string $salesChannelId,
        int $visibility = ProductVisibilityDefinition::VISIBILITY_ALL
    ) {
        parent::__construct(
            self::CONNECTION_AND,
            [
                new RangeFilter('product.visibilities.visibility', [RangeFilter::GTE => $visibility]),
                new EqualsFilter('product.visibilities.salesChannelId', $salesChannelId),
                new EqualsFilter('product.active', true),
            ]
        );
    }
}
return $customerReviews->first();
    }

    private function handlePointsAggregation(Request $request, Criteria $criteria, SalesChannelContext $context): void
    {
        $reviewFilters = [];
        $points = $request->get('points', []);

        if (\is_array($points) && \count($points) > 0) {
            $pointFilter = [];
            foreach ($points as $point) {
                $pointFilter[] = new RangeFilter('points', [
                    'gte' => $point - 0.5,
                    'lt' => $point + 0.5,
                ]);
            }

            $criteria->addPostFilter(new MultiFilter(MultiFilter::CONNECTION_OR, $pointFilter));
        }

        $reviewFilters[] = new EqualsFilter('status', true);
        if ($context->getCustomer() !== null) {
            $reviewFilters[] = new EqualsFilter('customerId', $context->getCustomer()->getId());
        }
new Request(['rating' => $input]),
            $this->createMock(SalesChannelContext::class)
        );

        $expected = new Filter(
            'rating',
            true,
            [
                new FilterAggregation(
                    'rating-exists',
                    new MaxAggregation('rating', 'product.ratingAverage'),
                    [new RangeFilter('product.ratingAverage', [RangeFilter::GTE => 0])]
                ),
            ],
            new RangeFilter('product.ratingAverage', [
                RangeFilter::GTE => $input,
            ]),
            $input
        );

        static::assertEquals($expected$result);
    }

    
$filterNoDateRange = new MultiFilter(
            MultiFilter::CONNECTION_AND,
            [
                new EqualsFilter('validFrom', null),
                new EqualsFilter('validUntil', null),
            ]
        );

        $filterStartedNoEndDate = new MultiFilter(
            MultiFilter::CONNECTION_AND,
            [
                new RangeFilter('validFrom', ['lte' => $todayStart]),
                new EqualsFilter('validUntil', null),
            ]
        );

        $filterActiveNoStartDate = new MultiFilter(
            MultiFilter::CONNECTION_AND,
            [
                new EqualsFilter('validFrom', null),
                new RangeFilter('validUntil', ['gt' => $todayEnd]),
            ]
        );

        
if (empty($query['field'])) {
                    throw DataAbstractionLayerException::invalidFilterQuery('Parameter "field" for suffix filter is missing.', $path . '/field');
                }

                if (!isset($query['value']) || $query['value'] === '') {
                    throw DataAbstractionLayerException::invalidFilterQuery('Parameter "value" for suffix filter is missing.', $path . '/value');
                }

                return new SuffixFilter(self::buildFieldName($definition$query['field'])$query['value']);

            case 'range':
                return new RangeFilter(self::buildFieldName($definition$query['field'])$query['parameters']);
            case 'until':
            case 'since':
                return self::getFilterByRelativeTime(self::buildFieldName($definition$query['field'])$query$path);
            case 'equalsAll':
                if (empty($query['field'])) {
                    throw DataAbstractionLayerException::invalidFilterQuery('Parameter "field" for equalsAny filter is missing.', $path . '/field');
                }

                if (empty($query['value'])) {
                    throw DataAbstractionLayerException::invalidFilterQuery('Parameter "value" for equalsAll filter is missing.', $path . '/value');
                }

                
/** * @depends testIndexing */
    public function testRangeFilter(IdsCollection $data): void
    {
        try {
            $searcher = $this->createEntitySearcher();
            // check simple range filter             $criteria = new Criteria($data->prefixed('p'));
            $criteria->addState(Criteria::STATE_ELASTICSEARCH_AWARE);
            $criteria->addFilter(new RangeFilter('product.stock', [RangeFilter::GTE => 10]));

            $products = $searcher->search($this->productDefinition, $criteria$this->context);
            static::assertCount(6, $products->getIds());
            static::assertSame(6, $products->getTotal());
        } catch (\Exception $e) {
            static::tearDown();

            throw $e;
        }
    }

    
$emailRecipientIds = array_map(fn ($id) => ['id' => $id]$emailRecipient->getIds());

        $this->newsletterRecipientRepository->delete($emailRecipientIds, Context::createDefaultContext());
    }

    private function getExpiredNewsletterRecipientCriteria(): Criteria
    {
        $criteria = new Criteria();

        $dateTime = (new \DateTime())->add(\DateInterval::createFromDateString('-30 days'));

        $criteria->addFilter(new RangeFilter(
            'createdAt',
            [
                RangeFilter::LTE => $dateTime->format(\DATE_ATOM),
            ]
        ));

        $criteria->addFilter(new EqualsFilter('status', 'notSet'));

        $criteria->setLimit(999);

        return $criteria;
    }
$connection
            ->expects(static::once())
            ->method('fetchOne')
            ->willReturn(current(array_column($filters, 'api_filter')));

        $criteria->setLimit(150);
        $criteria->addSorting(new FieldSorting('autoIncrement'));
        $filters = $criteria->getFilters();
        array_pop($filters);
        $criteria->resetFilters();
        $criteria->addFilter(...$filters);
        $criteria->setFilter('increment', new RangeFilter('autoIncrement', [RangeFilter::GTE => 0]));

        $definition = new ProductDefinition();
        $repository = new StaticEntityRepository([
            function DCriteria $actualCriteria, Context $actualContext) use ($criteria$context$ids): array {
                static::assertEquals($criteria$actualCriteria);
                static::assertEquals($context$actualContext);

                return $ids;
            },
            fn () => [],
        ]$definition);

        
use Shopware\Core\Framework\DataAbstractionLayer\Search\Filter\RangeFilter;

/** * @internal * * @covers \Shopware\Core\Framework\DataAbstractionLayer\Search\Filter\RangeFilter */
class RangeFilterTest extends TestCase
{
    public function testEncode(): void
    {
        $filter = new RangeFilter('foo', [
            RangeFilter::GT => 1,
        ]);

        static::assertEquals(
            [
                'field' => 'foo',
                'isPrimary' => false,
                'resolved' => null,
                'extensions' => [],
                'parameters' => [
                    RangeFilter::GT => 1,
                ],
if (!$source instanceof AdminApiSource) {
            throw new InvalidContextSourceException(AdminApiSource::class$context->getSource()::class);
        }

        $criteria = new Criteria();
        $isAdmin = $source->isAdmin();
        if (!$isAdmin) {
            $criteria->addFilter(new EqualsFilter('adminOnly', false));
        }

        if ($latestTimestamp) {
            $criteria->addFilter(new RangeFilter('createdAt', [
                RangeFilter::GT => $latestTimestamp,
            ]));
        }

        $criteria->addSorting(new FieldSorting('createdAt', FieldSorting::ASCENDING));
        $criteria->setLimit($limit);

        $notifications = $context->scope(Context::SYSTEM_SCOPE, function DContext $context) use ($criteria) {
            /** @var NotificationCollection $notifications */
            $notifications = $this->notificationRepository->search($criteria$context)->getEntities();

            
static::assertFalse($result->has($ids->get('product-2')));
    }

    /** * @depends testIndexing */
    public function testRangeFilter(IdsCollection $ids): void
    {
        $criteria = new Criteria($ids->prefixed('category-'));

        $criteria->addFilter(
            new RangeFilter('category.products.stock', [RangeFilter::GTE => 5])
        );

        $result = $this->getContainer()->get('category.repository')
            ->searchIds($criteria, Context::createDefaultContext());

        static::assertEquals(2, $result->getTotal());
        static::assertTrue($result->has($ids->get('category-1')));
        static::assertTrue($result->has($ids->get('category-2')));
        static::assertFalse($result->has($ids->get('category-3')));
    }

    
'Please add the argument "guests" to remove guests without orders or the argument "carts" to remove canceled carts. Use --all to clean both.'
            );
        }

        $days = (int) $input->getOption('days');

        if ($all || $type === self::TYPE_GUESTS) {
            $criteria = new Criteria();
            $criteria->addFilter(new EqualsFilter('guest', true));
            $criteria->addFilter(new EqualsFilter('orderCustomers.id', null));
            $criteria->addFilter(
                new RangeFilter(
                    'createdAt',
                    [
                        RangeFilter::LTE => (new \DateTime())->modify(-abs($days) . ' Day')
                            ->format(Defaults::STORAGE_DATE_TIME_FORMAT),
                    ]
                )
            );

            $ids = $this->customerRepository
                ->searchIds($criteria, Context::createDefaultContext())
                ->getIds();

            

    private function filterOutNewMedia(array $mediaIds, int $gracePeriodDays): array
    {
        if ($gracePeriodDays === 0) {
            return $mediaIds;
        }

        $threeDaysAgo = (new \DateTime())->sub(new \DateInterval(sprintf('P%dD', $gracePeriodDays)));
        $rangeFilter = new RangeFilter('uploadedAt', ['lt' => $threeDaysAgo->format(Defaults::STORAGE_DATE_TIME_FORMAT)]);

        $criteria = new Criteria($mediaIds);
        $criteria->addFilter($rangeFilter);

        /** @var array<string> $ids */
        $ids = $this->mediaRepo->searchIds($criteria, Context::createDefaultContext())->getIds();

        return $ids;
    }

    /** * @return \Generator<int, array<string>> */
    public function bench_load_product_listing_route_no_criteria(): void
    {
        $this->getContainer()->get(ProductListingRoute::class)
            ->load($this->ids->get(self::CATEGORY_KEY)new Request()$this->context, new Criteria());
    }

    #[Bench\Groups(['custom-pricing'])]     #[Bench\Assert('mean(variant.time.avg) < 35ms')]     public function bench_load_product_listing_route_only_active_and_price_below_80(): void
    {
        $criteria = (new Criteria())
            ->addFilter(new RangeFilter('price', [
                RangeFilter::GTE => 0.00,
                RangeFilter::LT => 80.00,
            ]))
            ->addFilter(new EqualsFilter('active', true));
        $this->getContainer()->get(ProductListingRoute::class)
            ->load($this->ids->get(self::CATEGORY_KEY)new Request()$this->context, $criteria);
    }

    protected static function getKernel(): KernelInterface
    {
        return self::getContainer()->get('kernel');
    }
Home | Imprint | This part of the site doesn't use cookies.