getPostFilters example



        $aggregation = new CardinalityAggregation('total-count');
        $aggregation->setScript($script);

        return $this->addPostFilterAggregation($criteria$definition$context$aggregation);
    }

    private function addPostFilterAggregation(Criteria $criteria, EntityDefinition $definition, Context $context, CardinalityAggregation $aggregation): AbstractAggregation
    {
        if (!$criteria->getPostFilters()) {
            return $aggregation;
        }

        $query = $this->criteriaParser->parseFilter(
            new MultiFilter(MultiFilter::CONNECTION_AND, $criteria->getPostFilters()),
            $definition,
            $definition->getEntityName(),
            $context
        );

        $filterAgg = new FilterAggregation('total-filtered-count', $query);
        
if ($criteria->getAssociations()) {
            return false;
        }

        if ($criteria->getAggregations()) {
            return false;
        }

        $filters = array_merge(
            $criteria->getFilters(),
            $criteria->getPostFilters()
        );

        // any kind of filters must be an own search         if (!empty($filters)) {
            return false;
        }

        if (empty($criteria->getIds())) {
            return false;
        }

        
/** @var RepositoryIterator<SystemConfigCollection> $iterator */
        $iterator = new RepositoryIterator($systemConfigRepository$context$criteria);

        $offset = 1;
        while (($result = $iterator->fetch()) !== null) {
            static::assertNotEmpty($result->getEntities()->first()?->getId());
            static::assertEquals(
                [new ContainsFilter('configurationKey', 'core')],
                $criteria->getFilters()
            );
            static::assertCount(0, $criteria->getPostFilters());
            static::assertEquals($offset$criteria->getOffset());
            ++$offset;
        }
    }

    public function testFetchIdsIsNotRunningInfinitely(): void
    {
        $context = Context::createDefaultContext();
        /** @var EntityRepository<SystemConfigCollection> $systemConfigRepository */
        $systemConfigRepository = $this->getContainer()->get('system_config.repository');

        
$array['includes'] = $criteria->getIncludes();
        }

        if (\count($criteria->getIds())) {
            $array['ids'] = $criteria->getIds();
        }

        if (\count($criteria->getFilters())) {
            $array['filter'] = array_map(static fn (Filter $filter) => QueryStringParser::toArray($filter)$criteria->getFilters());
        }

        if (\count($criteria->getPostFilters())) {
            $array['post-filter'] = array_map(static fn (Filter $filter) => QueryStringParser::toArray($filter)$criteria->getPostFilters());
        }

        if (\count($criteria->getAssociations())) {
            foreach ($criteria->getAssociations() as $assocName => $association) {
                $array['associations'][$assocName] = $this->convert($association);
            }
        }

        if (\count($criteria->getSorting())) {
            $array['sort'] = json_decode(json_encode($criteria->getSorting(), \JSON_THROW_ON_ERROR), true, 512, \JSON_THROW_ON_ERROR);

            
        if (\count($criteria->getSorting())) {
            return true;
        }

        // queries can only be handled in entity searcher         if (\count($criteria->getQueries())) {
            return true;
        }

        $filters = array_merge(
            $criteria->getFilters(),
            $criteria->getPostFilters()
        );

        /** @var CriteriaPartInterface $filter */
        foreach ($filters as $filter) {
            $accessors = $filter->getFields();
            foreach ($accessors as $accessor) {
                // get all fields of accessor to check which fields will be joined                 $definitionFields = EntityDefinitionQueryHelper::getFieldsOfAccessor($definition$accessor);

                // if the criteria contains an access to a OneToMany or ManyToMany field, the query would run into a temporary table.                 // to prevent overload for sql servers we will execute a minimal query with the ids at first
$filters = $this->groupFilters($definition$criteria$paths);

        $this->criteriaPartResolver->resolve($filters$definition$query$context);

        $this->criteriaPartResolver->resolve($criteria->getQueries()$definition$query$context);

        $this->criteriaPartResolver->resolve($criteria->getSorting()$definition$query$context);

        // do not use grouped filters, because the grouped filters are mapped flat and the logical OR/AND are removed         $filter = new AndFilter(array_merge(
            $criteria->getFilters(),
            $criteria->getPostFilters()
        ));

        $this->addFilter($definition$filter$query$context);

        $this->addQueries($definition$criteria$query$context);

        if ($criteria->getLimit() === 1) {
            $query->removeState(EntityDefinitionQueryHelper::HAS_TO_MANY_JOIN);
        }

        $this->addSortings($definition$criteria$criteria->getSorting()$query$context);

        


        return $records;
    }

    private function getTotalValue(Criteria $criteria, array $result): int
    {
        if (!$criteria->getGroupFields()) {
            return (int) $result['hits']['total']['value'];
        }

        if (!$criteria->getPostFilters()) {
            return (int) $result['aggregations']['total-count']['value'];
        }

        return (int) $result['aggregations']['total-filtered-count']['total-count']['value'];
    }

    private function sortByIdArray(array $ids, array $data): array
    {
        $sorted = [];

        foreach ($ids as $id) {
            
$handler = $handlerRegistry->getHandler($condition);

            if ($handler instanceof PartialConditionHandlerInterface) {
                $handler->handleFilter($condition$criteria$search$context);
            } else {
                $handler->handle($condition$criteria$search$context);
            }
        }

        $query = new BoolQuery();

        if ($search->getPostFilters()) {
            $query->add($search->getPostFilters());
        }

        if ($search->getQueries()->getQueries(BoolQuery::FILTER)) {
            foreach ($search->getQueries()->getQueries(BoolQuery::FILTER) as $filter) {
                $query->add($filter, BoolQuery::FILTER);
            }
        }
        if ($search->getQueries()) {
            $query->add($search->getQueries());
        }

        
$this->addExtensions($ids$searchResult$mapping);

        $result = new EntitySearchResult(ProductDefinition::ENTITY_NAME, $ids->getTotal()$searchResult->getEntities()$aggregations$origin$context->getContext());
        $result->addState(...$ids->getStates());

        return $result;
    }

    private function hasOptionFilter(Criteria $criteria): bool
    {
        $filters = $criteria->getPostFilters();

        $fields = [];
        foreach ($filters as $filter) {
            array_push($fields, ...$filter->getFields());
        }

        $fields = array_map(fn (string $field) => preg_replace('/^product./', '', $field)$fields);

        if (\in_array('options.id', $fields, true)) {
            return true;
        }

        
$processor = new AggregationListingProcessor(
            [$foo = new FooListingFilterHandler()],
            $this->createMock(EventDispatcherInterface::class)
        );

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

        $criteria = new Criteria();
        $processor->prepare(new Request()$criteria$context);

        static::assertCount(1, $criteria->getAggregations());
        static::assertCount(1, $criteria->getPostFilters());
        static::assertInstanceOf(TermsAggregation::class$criteria->getAggregation('foo'));
        static::assertTrue($foo->called);
    }

    public function testByPassProcess(): void
    {
        $processor = new AggregationListingProcessor(
            [$foo = new FooListingFilterHandler()],
            $this->createMock(EventDispatcherInterface::class)
        );

        
'id' => $id, 'name' => 'Test', 'territory' => 'test', 'code' => 'test' . $id],
            ],
            $context
        );

        $criteria = new Criteria([$id]);
        $locale = $repository->search($criteria$context);

        static::assertEquals([$id]$criteria->getIds());
        static::assertEmpty($criteria->getSorting());
        static::assertEmpty($criteria->getFilters());
        static::assertEmpty($criteria->getPostFilters());
        static::assertEmpty($criteria->getAggregations());
        static::assertEmpty($criteria->getAssociations());
        static::assertNull($criteria->getLimit());
        static::assertNull($criteria->getOffset());

        static::assertCount(1, $locale);

        static::assertTrue($locale->has($id));
        $locale = $locale->get($id);
        static::assertInstanceOf(LocaleEntity::class$locale);
        static::assertSame('Test', $locale->getName());
    }

    private function _read(
        Criteria $criteria,
        EntityDefinition $definition,
        Context $context,
        EntityCollection $collection,
        FieldCollection $fields,
        bool $performEmptySearch = false,
        array $partial = []
    ): EntityCollection {
        $hasFilters = !empty($criteria->getFilters()) || !empty($criteria->getPostFilters());
        $hasIds = !empty($criteria->getIds());

        if (!$performEmptySearch && !$hasFilters && !$hasIds) {
            return $collection;
        }

        if ($partial !== []) {
            $fields = $definition->getFields()->filter(function DField $field) use (&$partial) {
                if ($field->getFlag(PrimaryKey::class)) {
                    $partial[$field->getPropertyName()] = [];

                    
new MultiFilter(MultiFilter::CONNECTION_AND, $filters),
            $definition,
            $definition->getEntityName(),
            $context
        );

        $search->addQuery($query, BoolQuery::FILTER);
    }

    public function addPostFilters(EntityDefinition $definition, Criteria $criteria, Search $search, Context $context): void
    {
        $postFilters = $criteria->getPostFilters();
        if (empty($postFilters)) {
            return;
        }

        $query = $this->parser->parseFilter(
            new MultiFilter(MultiFilter::CONNECTION_AND, $postFilters),
            $definition,
            $definition->getEntityName(),
            $context
        );

        
$context->getItemRounding(),
            $ruleIds,
        ], \JSON_THROW_ON_ERROR));
    }

    public function getCriteriaHash(Criteria $criteria): string
    {
        return md5((string) json_encode([
            $criteria->getIds(),
            $criteria->getFilters(),
            $criteria->getTerm(),
            $criteria->getPostFilters(),
            $criteria->getQueries(),
            $criteria->getSorting(),
            $criteria->getLimit(),
            $criteria->getOffset() ?? 0,
            $criteria->getTotalCountMode(),
            $criteria->getGroupFields(),
            $criteria->getAggregations(),
            $criteria->getAssociations(),
        ], \JSON_THROW_ON_ERROR));
    }
}

    public function testManufacturerFilter(array $expected, Request $request): void
    {
        $criteria = new Criteria();
        $event = new ProductListingCriteriaEvent($request$criteria, Generator::createSalesChannelContext());
        $this->eventDispatcher->dispatch($event);

        if (empty($expected)) {
            static::assertCount(0, $criteria->getPostFilters());

            return;
        }

        static::assertCount(1, $criteria->getPostFilters());
        $filter = $criteria->getPostFilters()[0];

        static::assertInstanceOf(EqualsAnyFilter::class$filter);
        static::assertSame($expected$filter->getValue());
    }

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