hasAssociation example

->addAssociation('deliveryTime')
                ->addAssociation('cover.media')
            ;
        }

        if (!$this->hasAvailableFilter($criteria)) {
            $criteria->addFilter(
                new ProductAvailableFilter($context->getSalesChannel()->getId(), ProductVisibilityDefinition::VISIBILITY_LINK)
            );
        }

        if ($criteria->hasAssociation('productReviews')) {
            $association = $criteria->getAssociation('productReviews');
            $activeReviewsFilter = new MultiFilter(MultiFilter::CONNECTION_OR, [new EqualsFilter('status', true)]);
            if ($customer = $context->getCustomer()) {
                $activeReviewsFilter->addQuery(new EqualsFilter('customerId', $customer->getId()));
            }

            $association->addFilter($activeReviewsFilter);
        }
    }

    protected function defineFields(): FieldCollection
    {
$request = new Request([]$body[][][]);
        $request->setMethod(Request::METHOD_POST);

        $criteria = new Criteria();
        $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))
            
// if a specific id has been defined in the options and there is no corresponding attribute         // return false in order to avoid a fallback to the id which might be of another object         if (\is_string($options->id) && null === $request->attributes->get($options->id)) {
            return [];
        }

        $criteria = [];
        $metadata = $manager->getClassMetadata($options->class);

        foreach ($mapping as $attribute => $field) {
            if (!$metadata->hasField($field) && (!$metadata->hasAssociation($field) || !$metadata->isSingleValuedAssociation($field))) {
                continue;
            }

            $criteria[$field] = $request->attributes->get($attribute);
        }

        if ($options->stripNull) {
            $criteria = array_filter($criteriastatic fn ($value) => null !== $value);
        }

        return $criteria;
    }
$fields = array_filter($fieldsfn (Field $field) => $field instanceof AssociationField);

            if (empty($fields)) {
                continue;
            }

            $lastAssociationField = $fields[\count($fields) - 1];

            $path = array_map(fn (Field $field) => $field->getPropertyName()$fields);

            $association = implode('.', $path);
            if ($criteria->hasAssociation($association)) {
                continue;
            }

            $criteria->addAssociation($association);

            $translationField = $lastAssociationField->getReferenceDefinition()->getTranslationField();
            if (!$translationField) {
                continue;
            }

            // filter the associations that have no translations in given language,
return true;
                }

                return isset($partial[$field->getPropertyName()]);
            });
        }

        // always add the criteria fields to the collection, otherwise we have conflicts between criteria.fields and criteria.association logic         $fields = $this->addAssociationFieldsToCriteria($criteria$definition$fields);

        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())) {
            

                SalesChannelContextService::CUSTOMER_ID => $customerId,
            ]
        );
    }

    public function testLoad(): void
    {
        $this->eventDispatcherMock->expects(static::once())->method('dispatch')->with(static::callback(static function DAttachmentLoaderCriteriaEvent $event) {
            $criteria = $event->getCriteria();

            return $criteria->hasAssociation('documentMediaFile') && $criteria->hasAssociation('documentType');
        }));

        $cart = $this->generateDemoCart(2);
        $orderId = $this->persistCart($cart);

        $operation = new DocumentGenerateOperation($orderId);

        $document = $this->documentGenerator->generate(InvoiceRenderer::TYPE, [$orderId => $operation]$this->context)->getSuccess()->first();

        static::assertNotNull($document);

        
class AssociationLoadingProcessorTest extends TestCase
{
    public function testPrepare(): void
    {
        $request = new Request();
        $criteria = new Criteria();
        $context = $this->createMock(SalesChannelContext::class);

        $processor = new AssociationLoadingListingProcessor();
        $processor->prepare($request$criteria$context);

        static::assertTrue($criteria->hasAssociation('manufacturer'));
        static::assertTrue($criteria->hasAssociation('options'));
    }
}
if (!$em) {
                throw new ConstraintDefinitionException(sprintf('Unable to find the object manager associated with an entity of class "%s".', get_debug_type($entity)));
            }
        }

        $class = $em->getClassMetadata($entity::class);

        $criteria = [];
        $hasIgnorableNullValue = false;

        foreach ($fields as $fieldName) {
            if (!$class->hasField($fieldName) && !$class->hasAssociation($fieldName)) {
                throw new ConstraintDefinitionException(sprintf('The field "%s" is not mapped by Doctrine, so it cannot be validated for uniqueness.', $fieldName));
            }

            $fieldValue = $class->reflFields[$fieldName]->getValue($entity);

            if (null === $fieldValue && $this->ignoreNullForField($constraint$fieldName)) {
                $hasIgnorableNullValue = true;

                continue;
            }

            
$this->registry = $registry;
    }

    public function guessType(string $class, string $property): ?TypeGuess
    {
        if (!$ret = $this->getMetadata($class)) {
            return new TypeGuess(TextType::class[], Guess::LOW_CONFIDENCE);
        }

        [$metadata$name] = $ret;

        if ($metadata->hasAssociation($property)) {
            $multiple = $metadata->isCollectionValuedAssociation($property);
            $mapping = $metadata->getAssociationMapping($property);

            return new TypeGuess(EntityType::class['em' => $name, 'class' => $mapping['targetEntity'], 'multiple' => $multiple], Guess::HIGH_CONFIDENCE);
        }

        return match ($metadata->getTypeOfField($property)) {
            Types::ARRAY,
            Types::SIMPLE_ARRAY => new TypeGuess(CollectionType::class[], Guess::MEDIUM_CONFIDENCE),
            Types::BOOLEAN => new TypeGuess(CheckboxType::class[], Guess::HIGH_CONFIDENCE),
            Types::DATETIME_MUTABLE,
            


        return $properties;
    }

    public function getTypes(string $class, string $property, array $context = []): ?array
    {
        if (null === $metadata = $this->getMetadata($class)) {
            return null;
        }

        if ($metadata->hasAssociation($property)) {
            $class = $metadata->getAssociationTargetClass($property);

            if ($metadata->isSingleValuedAssociation($property)) {
                if ($metadata instanceof ClassMetadataInfo) {
                    $associationMapping = $metadata->getAssociationMapping($property);

                    $nullable = $this->isAssociationNullable($associationMapping);
                } else {
                    $nullable = false;
                }

                

    public function getAssociation(string $path): Criteria
    {
        $parts = explode('.', $path);

        $criteria = $this;
        foreach ($parts as $part) {
            if ($part === 'extensions') {
                continue;
            }

            if (!$criteria->hasAssociation($part)) {
                $criteria->associations[$part] = new Criteria();
            }

            $criteria = $criteria->associations[$part];
        }

        return $criteria;
    }

    public function addFilter(Filter ...$queries): self
    {
        
public function testLoadCanStillBeCalledWithOneParameter(): void
    {
        $themeProvider = new DatabaseAvailableThemeProvider(new StaticEntityRepository([new SalesChannelCollection()]));

        static::assertEquals([]$themeProvider->load(Context::createDefaultContext()));
    }

    public function testThemeProviderIsSearchingForStorefrontsWithThemes(): void
    {
        $salesChannelRepository = new StaticEntityRepository([
            static function DCriteria $criteria, Context $context): EntitySearchResult {
                static::assertTrue($criteria->hasAssociation('themes'));

                static::assertEquals([
                    new EqualsFilter('typeId', Defaults::SALES_CHANNEL_TYPE_STOREFRONT),
                ]$criteria->getFilters());

                return new EntitySearchResult(
                    SalesChannelDefinition::ENTITY_NAME,
                    0,
                    new SalesChannelCollection(),
                    null,
                    $criteria,
                    
$tokenFactory = $this->createMock(JWTFactoryV2::class);
        $tokenFactory->expects(static::once())->method('parseToken')->with('paymentToken')->willReturn(new TokenStruct('id', 'token', 'paymentMethodId', $transactionId, 'finishUrl', \PHP_INT_MAX));
        $tokenFactory->expects(static::once())->method('invalidateToken')->with('token');

        $eventDispatcher = $this->createMock(EventDispatcherInterface::class);
        $eventDispatcher->expects(static::once())->method('dispatch')->with(static::isInstanceOf(FinalizePaymentOrderTransactionCriteriaEvent::class));

        $transactionRepository = $this->createMock(EntityRepository::class);
        $transactionRepository->expects(static::once())->method('search')->with(static::callback(function DCriteria $criteria) use ($transactionId) {
            static::assertEquals($transactionId$criteria->getIds()[0]);
            static::assertSame('payment-service::load-transaction', $criteria->getTitle());
            static::assertTrue($criteria->hasAssociation('order'));
            static::assertTrue($criteria->hasAssociation('paymentMethod'));

            return true;
        }))->willReturn(new EntitySearchResult('order_transaction', 1, new OrderTransactionCollection([$transaction]), null, new Criteria()$context->getContext()));

        $struct = new AsyncPaymentTransactionStruct($transaction$order, '');
        $paymentStructFactory = $this->createMock(AbstractPaymentTransactionStructFactory::class);
        $paymentStructFactory->expects(static::once())->method('async')->willReturn($struct);

        $paymentHandler = $this->createMock(AsynchronousPaymentHandlerInterface::class);
        $paymentHandler->expects(static::once())->method('finalize')->with($struct$request$context);

        

        $ids = $classMetadata->getIdentifierFieldNames();
        $idType = $classMetadata->getTypeOfField(current($ids));

        $this->om = $om;
        $this->classMetadata = $classMetadata;
        $this->singleId = 1 === \count($ids);
        $this->intId = $this->singleId && \in_array($idType['integer', 'smallint', 'bigint']);
        $this->idField = current($ids);

        // single field association are resolved, since the schema column could be an int         if ($this->singleId && $classMetadata->hasAssociation($this->idField)) {
            $this->associationIdReader = new self($om$om->getClassMetadata(
                $classMetadata->getAssociationTargetClass($this->idField)
            ));

            $this->singleId = $this->associationIdReader->isSingleId();
            $this->intId = $this->associationIdReader->isIntId();
        }
    }

    /** * Returns whether the class has a single-column ID. */
Home | Imprint | This part of the site doesn't use cookies.