getAssociations example

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

        $request->query->set('no-aggregations', true);
        $this->getContainer()->get(CompositeListingProcessor::class)->prepare($request$criteria$context);
        static::assertEmpty($criteria->getAggregations());

        $request->query->set('only-aggregations', true);
        $this->getContainer()->get(CompositeListingProcessor::class)->prepare($request$criteria$context);
        static::assertEmpty($criteria->getSorting());
        static::assertEmpty($criteria->getAssociations());
        static::assertSame(0, $criteria->getLimit());
        static::assertSame(Criteria::TOTAL_COUNT_MODE_NONE, $criteria->getTotalCountMode());
    }
}
$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());
    }

    

        $privilege = $entity . ':' . AclRoleDefinition::PRIVILEGE_READ;

        $missing = [];

        if (!$context->isAllowed($privilege)) {
            $missing[] = $privilege;
        }

        $definition = $this->registry->getByEntityName($entity);

        foreach ($criteria->getAssociations() as $field => $nested) {
            $association = $definition->getField($field);

            if (!$association instanceof AssociationField) {
                throw new AssociationNotFoundException($field);
            }

            $reference = $association->getReferenceDefinition()->getEntityName();
            if ($association instanceof ManyToManyAssociationField) {
                $reference = $association->getToManyReferenceDefinition()->getEntityName();
            }

            
$criteria = new Criteria();
        $config = new Config(
            [
                'name',
            ],
            [],
            []
        );
        $criteriaBuild->enrichCriteria($config$criteria);

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

    public function testAssociations(): void
    {
        $criteriaBuild = new CriteriaBuilder($this->getContainer()->get(ProductDefinition::class));

        $criteria = new Criteria();
        $config = new Config(
            [
                'name',
                'translations.name',
                

    public function generate(array $ids, string $template, SeoUrlRouteInterface $route, Context $context, SalesChannelEntity $salesChannel): iterable
    {
        $criteria = new Criteria($ids);
        $route->prepareCriteria($criteria$salesChannel);

        $config = $route->getConfig();

        $repository = $this->definitionRegistry->getRepository($config->getDefinition()->getEntityName());

        $associations = $this->getAssociations($template$repository->getDefinition());
        $criteria->addAssociations($associations);

        $criteria->setLimit(50);

        /** @var RepositoryIterator<LandingPageCollection|CategoryCollection|ProductCollection> $iterator */
        $iterator = $context->enableInheritance(static fn (Context $context): RepositoryIterator => new RepositoryIterator($repository$context$criteria));

        $this->setTwigTemplate($config$template);

        while ($entities = $iterator->fetch()) {
            yield from $this->generateUrls($route$config$salesChannel$entities);
        }
|| !empty($fieldCriteria->getSorting())
            || !empty($fieldCriteria->getFilters())
            || !empty($fieldCriteria->getPostFilters())
        ;
    }

    private function addAssociationFieldsToCriteria(
        Criteria $criteria,
        EntityDefinition $definition,
        FieldCollection $fields
    ): FieldCollection {
        foreach ($criteria->getAssociations() as $fieldName => $_fieldCriteria) {
            $field = $definition->getFields()->get($fieldName);
            if (!$field) {
                $this->logger->warning(
                    sprintf('Criteria association "%s" could not be resolved. Double check your Criteria!', $fieldName)
                );

                continue;
            }

            $fields->add($field);
        }

        
throw new AccessDeniedHttpException(
                sprintf(
                    'Read access to entity "%s" not allowed for scope "%s".',
                    $definition->getEntityName(),
                    $context->getScope()
                )
            );
        }

        $this->validateCriteriaAssociation(
            $definition,
            $event->getCriteria()->getAssociations(),
            $context
        );
    }

    public function validateWriteCommands(PreWriteValidationEvent $event): void
    {
        foreach ($event->getCommands() as $command) {
            // Don't validate commands that fake operations on DB level, e.g. cascade deletes             if (!$command->isValid()) {
                continue;
            }

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

            foreach ($array['sort'] as &$sort) {
                $sort['order'] = $sort['direction'];
                unset($sort['direction']);
            }
#[Package('checkout')] class OrderDocumentCriteriaFactoryTest extends TestCase
{
    public function testCreate(): void
    {
        $id = Uuid::randomHex();

        $criteria = OrderDocumentCriteriaFactory::create([$id], 'test');

        static::assertEquals($id$criteria->getIds()[0]);

        $associations = $criteria->getAssociations();

        static::assertArrayHasKey('lineItems', $associations);
        static::assertArrayHasKey('transactions', $associations);
        static::assertArrayHasKey('currency', $associations);
        static::assertArrayHasKey('language', $associations);
        static::assertArrayHasKey('addresses', $associations);
        static::assertArrayHasKey('orderCustomer', $associations);

        $transactionCriteria = $associations['transactions'];
        static::assertInstanceOf(Criteria::class$transactionCriteria);
        static::assertInstanceOf(Criteria::class$transactionCriteria->getAssociations()['paymentMethod']);

        
if ($definition instanceof SalesChannelDefinitionInterface) {
                $definition->processCriteria($criteria$salesChannelContext);

                $eventName = \sprintf('sales_channel.%s.process.criteria', $definition->getEntityName());
                $event = new SalesChannelProcessCriteriaEvent($criteria$salesChannelContext);

                $this->eventDispatcher->dispatch($event$eventName);
            }

            $processed[$definition::class] = true;

            foreach ($criteria->getAssociations() as $associationName => $associationCriteria) {
                // find definition                 $field = $definition->getField($associationName);
                if (!$field instanceof AssociationField) {
                    continue;
                }

                $referenceDefinition = $field->getReferenceDefinition();
                $queue[] = ['definition' => $referenceDefinition, 'criteria' => $associationCriteria];
            }
        }
    }
}
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());
        static::assertSame(Criteria::TOTAL_COUNT_MODE_NONE, $criteria->getTotalCountMode());
        static::assertEmpty($criteria->getSorting());
        static::assertEmpty($criteria->getAssociations());
    }
}
// sortings must be an own search         if (\count($criteria->getSorting())) {
            return false;
        }

        // queries must be an own search         if (\count($criteria->getQueries())) {
            return false;
        }

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

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

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

        
public function testInvalidAssociationsCriteria(): void
    {
        $payload = [
            'associations' => [
                'prices' => 'invalid',
            ],
        ];

        $criteria = $this->requestCriteriaBuilder->fromArray($payloadnew Criteria()$this->staticDefinitionRegistry->get(ProductDefinition::class), Context::createDefaultContext());

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

    /** * @dataProvider providerTotalCount */
    public function testDifferentTotalCount(mixed $totalCountMode, int $expectedMode): void
    {
        $payload = [
            'total-count-mode' => $totalCountMode,
        ];

        
$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));
    }
}
$productExport->getStorefrontSalesChannelId(),
            $productExport->getSalesChannelDomain()->getLanguageId(),
            $this->languageLocaleProvider->getLocaleForLanguageId($productExport->getSalesChannelDomain()->getLanguageId()),
            $context->getContext()
        );

        $filters = $this->productStreamBuilder->buildFilters(
            $productExport->getProductStreamId(),
            $context->getContext()
        );

        $associations = $this->getAssociations($productExport$context);

        $criteria = new Criteria();
        $criteria->setTitle('product-export::products');

        $criteria
            ->addFilter(...$filters)
            ->setOffset($exportBehavior->offset())
            ->setLimit($this->readBufferSize);

        foreach ($associations as $association) {
            $criteria->addAssociation($association);
        }
Home | Imprint | This part of the site doesn't use cookies.