getAggregations example

$response = [
            'total' => $searchResult->getTotal(),
            'data' => $decoded,
        ];

        $fields = new ResponseFields(
            $request->get('includes', [])
        );

        $aggregations = [];
        foreach ($searchResult->getAggregations() as $aggregation) {
            $aggregations[$aggregation->getName()] = $this->structEncoder->encode(
                $aggregation,
                $fields
            );
        }

        $response['aggregations'] = $aggregations;

        return new JsonResponse($response);
    }

    
while (($loop = $repositoryIterator->fetch()) !== null) {
            $entities = $loop->getEntities();

            $mergedOptions->merge($entities);
        }

        // group options by their property-group         $grouped = $mergedOptions->groupByPropertyGroups();
        $grouped->sortByPositions();
        $grouped->sortByConfig();

        $aggregations = $result->getAggregations();

        // remove id results to prevent wrong usages         $aggregations->remove('properties');
        $aggregations->remove('configurators');
        $aggregations->remove('options');

        $aggregations->add(new EntityResult('properties', $grouped));
    }

    /** * @param array<string>|null $groupIds */

class BehaviorProcessorTest extends TestCase
{
    public function testPrepareWithNoAggregations(): void
    {
        $request = new Request(['no-aggregations' => true]);
        $criteria = new Criteria();
        $context = $this->createMock(SalesChannelContext::class);

        (new BehaviorListingProcessor())->prepare($request$criteria$context);

        static::assertEmpty($criteria->getAggregations());
    }

    public function testPrepareWithOnlyAggregations(): void
    {
        $request = new Request(['only-aggregations' => true]);
        $criteria = new Criteria();
        $context = $this->createMock(SalesChannelContext::class);

        (new BehaviorListingProcessor())->prepare($request$criteria$context);

        static::assertSame(0, $criteria->getLimit());
        

    public function search(Criteria $criteria, SalesChannelContext $salesChannelContext): EntitySearchResult
    {
        $criteria = clone $criteria;

        $this->processCriteria($criteria$salesChannelContext);

        $aggregations = null;
        if ($criteria->getAggregations()) {
            $aggregations = $this->aggregate($criteria$salesChannelContext);
        }
        if (!RepositorySearchDetector::isSearchRequired($this->definition, $criteria)) {
            $entities = $this->read($criteria$salesChannelContext);

            return new EntitySearchResult($this->definition->getEntityName()$entities->count()$entities$aggregations$criteria$salesChannelContext->getContext());
        }

        $ids = $this->doSearch($criteria$salesChannelContext);

        if (empty($ids->getIds())) {
            
return $entities;
    }

    /** * @return EntitySearchResult<TEntityCollection> */
    private function _search(Criteria $criteria, Context $context): EntitySearchResult
    {
        $criteria = clone $criteria;
        $aggregations = null;
        if ($criteria->getAggregations()) {
            $aggregations = $this->aggregate($criteria$context);
        }

        if (!RepositorySearchDetector::isSearchRequired($this->definition, $criteria)) {
            $this->eventDispatcher->dispatch(
                new EntitySearchedEvent($criteria$this->definition, $context)
            );
            $entities = $this->read($criteria$context);

            return new EntitySearchResult($this->definition->getEntityName()$entities->count()$entities$aggregations$criteria$context);
        }

        

        $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)
        );

        

            'testSearchAggregation' => [
                [
                    'aggregations' => [
                        ['name' => 'sum', 'type' => 'sum', 'field' => 'price.gross'],
                    ],
                ],
                'search',
                $ids,
                function DEntitySearchResult $result): void {
                    static::assertCount(4, $result);
                    $agg = $result->getAggregations()->get('sum');
                    static::assertInstanceOf(SumResult::class$agg);
                    static::assertEquals(600, $agg->getSum());
                },
            ],
            'testSearchSort' => [
                [
                    'sort' => [['field' => 'id']],
                ],
                'search',
                $ids,
                function DEntitySearchResult $result): void {
                    


        $criteria->addAggregation(
            new TermsAggregation('filters', 'properties.id')
        );

        $criteria->setLimit(0);

        $products = $this->getContainer()->get('product.repository')
            ->search($criteria, Context::createDefaultContext());

        $aggregation = $products->getAggregations()->get('filters');

        static::assertInstanceOf(TermsResult::class$aggregation);

        static::assertContains($ids->get('red')$aggregation->getKeys());
        static::assertContains($ids->get('yellow')$aggregation->getKeys());
        static::assertContains($ids->get('XL')$aggregation->getKeys());
        static::assertContains($ids->get('L')$aggregation->getKeys());
    }

    /** * @depends testIndexing */
// product 1 has all available variants         static::assertTrue($listing->has($this->testData->getId('product1-red')));
        static::assertTrue($listing->has($this->testData->getId('product1-green')));
        static::assertTrue($listing->has($this->testData->getId('product1-blue')));

        // product 2 has all available variants         static::assertTrue($listing->has($this->testData->getId('product2-green')));
        static::assertTrue($listing->has($this->testData->getId('product2-red')));

        /** @var EntityResult<PropertyGroupCollection> $result */
        $result = $listing->getAggregations()->get('properties');
        $options = $result->getEntities();

        $ids = array_keys($options->getOptionIdMap());

        static::assertContains($this->testData->getId('green')$ids);
        static::assertContains($this->testData->getId('red')$ids);
        static::assertContains($this->testData->getId('blue')$ids);
    }

    public function testListingWithFilterEnabled(): void
    {
        

        self::assertVariationsInListing($products[
            $this->testData->getId('product4-green-l-steel'),
            $this->testData->getId('product4-green-xl-steel'),
        ]);

        self::assertVariationsInListing($products[
            $this->testData->getId('product5-red'),
            $this->testData->getId('product5-green'),
        ]);

        $result = $listing->getAggregations()->get('properties');
        static::assertInstanceOf(EntityResult::class$result);

        $options = $result->getEntities();
        static::assertInstanceOf(PropertyGroupCollection::class$options);
        $ids = array_keys($options->getOptionIdMap());

        static::assertContains($this->testData->getId('green')$ids);
        static::assertContains($this->testData->getId('red')$ids);
        static::assertContains($this->testData->getId('xl')$ids);
        static::assertContains($this->testData->getId('l')$ids);
        static::assertContains($this->testData->getId('iron')$ids);
        

        }

        if (\count($criteria->getGroupFields())) {
            $array['grouping'] = [];

            foreach ($criteria->getGroupFields() as $groupField) {
                $array['grouping'][] = $groupField->getField();
            }
        }

        if (\count($criteria->getAggregations())) {
            $array['aggregations'] = $this->aggregationParser->toArray($criteria->getAggregations());
        }

        return $array;
    }
}
new TermsResult('options', [
                    new Bucket('xl', 1, null),
                    new Bucket('l', 1, null),
                ]),
            ]),
            new Criteria(),
            Context::createDefaultContext()
        );

        $handler->process($request$result$context);

        static::assertTrue($result->getAggregations()->has('properties'));
        static::assertFalse($result->getAggregations()->has('options'));

        $properties = $result->getAggregations()->get('properties');

        static::assertInstanceOf(EntityResult::class$properties);
        static::assertCount(2, $properties->getEntities());

        $color = $properties->getEntities()->first();
        static::assertInstanceOf(Entity::class$color);
        static::assertEquals('color', $color->get('id'));

        


    public function getDecorated(): AbstractListingProcessor
    {
        throw new DecorationPatternException(self::class);
    }

    public function prepare(Request $request, Criteria $criteria, SalesChannelContext $context): void
    {
        $filters = $this->getFilters($request$context);

        $aggregations = $this->getAggregations($request$filters);

        foreach ($aggregations as $aggregation) {
            $criteria->addAggregation($aggregation);
        }

        foreach ($filters as $filter) {
            if ($filter->isFiltered()) {
                $criteria->addPostFilter($filter->getFilter());
            }
        }

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

        $context = $this->getContainer()->get(SalesChannelContextFactory::class)
            ->create(Uuid::randomHex(), TestDefaults::SALES_CHANNEL);

        $listing = $this->getContainer()
            ->get(ProductListingRoute::class)
            ->load($categoryId$request$contextnew Criteria())
            ->getResult();

        $aggregation = $listing->getAggregations()->get($expected['aggregation']);

        if ($expected['instanceOf'] === null) {
            static::assertNull($aggregation);
        } else {
            static::assertInstanceOf($expected['instanceOf']$aggregation);
        }

        if ($expected['aggregation'] === 'properties' && isset($expected['propertyWhitelistIds'])) {
            static::assertInstanceOf(EntityResult::class$aggregation);
            /** @var PropertyGroupCollection $properties */
            $properties = $aggregation->getEntities();

            
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));
    }
}
Home | Imprint | This part of the site doesn't use cookies.