getSorting example

$repository->create(
            [
                ['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);
        
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);

            foreach ($array['sort'] as &$sort) {
                $sort['order'] = $sort['direction'];
                unset($sort['direction']);
            }
            unset($sort);
        }

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

            
new RangeFilter('product.width', [
                    'gte' => 120,
                    'lte' => 180,
                ]),
            ]
        ));
        $expectedCriteria->setLimit(50);

        /** @var Criteria $criteria */
        /** @phpstan-ignore-next-line - will fail because return type of getIterator will change */
        foreach ($collection->getIterator()->current() as $criteria) {
            static::assertEquals($expectedCriteria->getSorting()$criteria->getSorting());
            static::assertEquals($expectedCriteria->getLimit()$criteria->getLimit());
            /** @var MultiFilter $expectedMultiFilter */
            $expectedMultiFilter = $expectedCriteria->getFilters()[0];
            /** @var MultiFilter $multiFilter */
            $multiFilter = $expectedCriteria->getFilters()[0];
            static::assertEquals($expectedMultiFilter->getQueries()[0]$multiFilter->getQueries()[0]);
            /** @var RangeFilter $expectedRangeFilter */
            $expectedRangeFilter = $expectedMultiFilter->getQueries()[1];
            /** @var RangeFilter $rangeFilter */
            $rangeFilter = $expectedMultiFilter->getQueries()[1];
            static::assertEquals($rangeFilter->getField()$rangeFilter->getField());
            


    /** * {@inheritdoc} */
    public function handle(
        CriteriaPartInterface $criteriaPart,
        Criteria $criteria,
        Search $search,
        ShopContextInterface $context
    ) {
        $search->addSort($this->getSorting($criteriaPart));
    }

    private function getSorting(SearchRankingSorting $criteriaPart): FieldSort
    {
        return new FieldSort('_score', strtolower($criteriaPart->getDirection()));
    }
}

        if ($aggregation instanceof DateHistogramAggregation) {
            $data = [
                'name' => $aggregation->getName(),
                'type' => 'histogram',
                'interval' => $aggregation->getInterval(),
                'format' => $aggregation->getFormat(),
                'field' => $aggregation->getField(),
                'timeZone' => $aggregation->getTimeZone(),
            ];

            if ($aggregation->getSorting()) {
                $data['sort'] = [
                    'order' => $aggregation->getSorting()->getDirection(),
                    'naturalSorting' => $aggregation->getSorting()->getNaturalSorting(),
                    'field' => $aggregation->getSorting()->getField(),
                ];
            }

            if ($aggregation->getAggregation()) {
                $data['aggregation'] = $this->aggregationToArray($aggregation->getAggregation());
            }

            
$context = $this->createSalesChannelContextWithNavigation();

        /** @var SearchPageLoadedEvent $homePageLoadedEvent */
        $homePageLoadedEvent = null;
        $this->catchEvent(SearchPageLoadedEvent::class$homePageLoadedEvent);

        $page = $this->getPageLoader()->load($request$context);

        static::assertSame(
            ProductListingFeaturesSubscriber::DEFAULT_SEARCH_SORT,
            $page->getListing()->getSorting()
        );
    }

    public function testItDisplaysCorrectTitle(): void
    {
        $request = new Request(['search' => self::TEST_TERM]);

        $context = $this->createSalesChannelContextWithNavigation();

        /** @var SearchPageLoadedEvent $homePageLoadedEvent */
        $homePageLoadedEvent = null;
        
$this->requestCriteriaBuilder->handleRequest(
            $request,
            $criteria,
            $this->staticDefinitionRegistry->get(ProductDefinition::class),
            Context::createDefaultContext()
        );

        static::assertTrue($criteria->hasAssociation('prices'));
        $nested = $criteria->getAssociation('prices');

        static::assertCount(1, $nested->getFilters());
        static::assertCount(1, $nested->getSorting());
    }

    public function testCriteriaToArray(): void
    {
        $criteria = (new Criteria())
            ->addSorting(new FieldSorting('order.createdAt', FieldSorting::DESCENDING))
            ->addSorting(new CountSorting('transactions.id', CountSorting::ASCENDING))
            ->addAssociation('transactions.paymentMethod')
            ->addAssociation('deliveries.shippingMethod')
            ->setLimit(1)
            ->setOffset((1 - 1) * 1)
            


        $maxValue = (int) $this->connection->fetchColumn('SELECT MAX(position) FROM s_categories_manual_sorting WHERE category_id = ?', [
            $categoryId,
        ]);

        $productIds = array_map('intval', array_keys($positions));
        $positionValues = array_values($positions);
        $sorting = $this->getSorting($categoryId$sortingId);
        $maxPosition = empty($positionValues) ? 0 : max($positionValues);
        $hasFoundMaxPosition = false;

        $products = $this->productLoader->load($categoryId, 0, max($maxPosition$maxValue)$sorting)['data'];
        $backlogs = [];

        $i = 1;
        foreach ($products as $key => $product) {
            if (\in_array((int) $product['id']$productIds, true)) {
                continue;
            }

            


    /** * {@inheritdoc} */
    public function handle(
        CriteriaPartInterface $criteriaPart,
        Criteria $criteria,
        Search $search,
        ShopContextInterface $context
    ) {
        $search->addSort($this->getSorting($criteriaPart));
    }

    private function getSorting(ProductStockSorting $criteriaPart): FieldSort
    {
        return new FieldSort('stock', strtolower($criteriaPart->getDirection())['unmapped_type' => 'keyword']);
    }
}


        $config = Config::fromLog($this->logEntity);
        $criteriaBuilder = new CriteriaBuilder($this->repository->getDefinition());

        $criteria = $criteria === null ? new Criteria() : clone $criteria;
        $criteriaBuilder->enrichCriteria($config$criteria);

        $enrichEvent = new EnrichExportCriteriaEvent($criteria$this->logEntity);
        $this->eventDispatcher->dispatch($enrichEvent);

        if ($criteria->getSorting() === []) {
            // default sorting             $criteria->addSorting(new FieldSorting('createdAt', FieldSorting::ASCENDING));
        }
        $criteria->addSorting(new FieldSorting('id'));

        $criteria->setOffset($offset);
        $criteria->setTotalCountMode(Criteria::TOTAL_COUNT_MODE_EXACT);

        $criteria->setLimit($this->exportLimit <= 0 ? 250 : $this->exportLimit);
        $fullExport = $this->exportLimit <= 0;

        
$level = $level->getAggregation();
        /** @var TermsAggregation $level */
        static::assertInstanceOf(TermsAggregation::class$level);
        static::assertSame('level2', $level->getName());
        static::assertSame(10, $level->getLimit());

        $level = $level->getAggregation();
        /** @var TermsAggregation $level */
        static::assertInstanceOf(TermsAggregation::class$level);
        static::assertSame('level3', $level->getName());
        static::assertEquals(new FieldSorting('product.price')$level->getSorting());
    }

    public function testICanCreateAFilterAggregation(): void
    {
        $criteria = new Criteria();
        $exception = new SearchRequestException();

        $this->parser->buildAggregations(
            $this->getContainer()->get(ProductDefinition::class),
            [
                'aggregations' => [
                    [

        throw new DecorationPatternException(self::class);
    }

    #[Route(path: '/store-api/shipping-method', name: 'store-api.shipping.method', methods: ['GET', 'POST'], defaults: ['_entity' => 'shipping_method'])]     public function load(Request $request, SalesChannelContext $context, Criteria $criteria): ShippingMethodRouteResponse
    {
        $criteria
            ->addFilter(new EqualsFilter('active', true))
            ->addAssociation('media');

        if (empty($criteria->getSorting())) {
            $criteria->addSorting(new FieldSorting('position')new FieldSorting('name', FieldSorting::ASCENDING));
        }

        $result = $this->shippingMethodRepository->search($criteria$context);

        $shippingMethods = $result->getEntities();

        if ($request->query->getBoolean('onlyAvailable') || $request->request->getBoolean('onlyAvailable')) {
            $shippingMethods = $shippingMethods->filterByActiveRules($context);
        }

        
$slot->setType('product-listing');
        $slot->addTranslated('config', $slotConfig);

        $this->productListingCMSElementResolver->enrich($slot$resolverContext$result);

        /** @var ProductListingStruct $data */
        $data = $slot->getData();

        /** @var ProductListingResult $listing */
        $listing = $data->getListing();

        static::assertEquals('name-asc', $listing->getSorting());

        if ($availableSortings) {
            foreach ($listing->getAvailableSortings() as $availableSorting) {
                static::assertArrayHasKey($availableSorting->getKey()$availableSortings);
            }
        }
    }

    public function testUnavailableSortingThrowsException(): void
    {
        $slotConfig = [
            
/** * @dataProvider listSortingProvider * * @param array<string, string> $expectedFields */
    public function testListSorting(array $expectedFields, Request $request): void
    {
        $criteria = new Criteria();
        $event = new ProductListingCriteriaEvent($request$criteria, Generator::createSalesChannelContext());
        $this->eventDispatcher->dispatch($event);

        $sortings = $criteria->getSorting();

        static::assertCount(\count($expectedFields)$sortings);

        foreach ($sortings as $sorting) {
            static::assertArrayHasKey($sorting->getField()$expectedFields);
            static::assertSame($sorting->getDirection()$expectedFields[$sorting->getField()]);
        }
    }

    /** * @dataProvider searchSortingProvider * * @group slow * * @param array<string, string> $expectedFields */
if ($definition->isInheritanceAware() && $criteria->hasAssociation('parent')) {
            throw new ParentAssociationCanNotBeFetched();
        }

        $rows = $this->fetch($criteria$definition$context$fields$partial);

        $collection = $this->hydrator->hydrate($collection$definition->getEntityClass()$definition$rows$definition->getEntityName()$context$partial);

        $collection = $this->fetchAssociations($criteria$definition$context$collection$fields$partial);

        $hasIds = !empty($criteria->getIds());
        if ($hasIds && empty($criteria->getSorting())) {
            $collection->sortByIdArray($criteria->getIds());
        }

        return $collection;
    }

    /** * @param array<string, mixed> $partial */
    private function joinBasic(
        EntityDefinition $definition,
        
Home | Imprint | This part of the site doesn't use cookies.