Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@
"conflict": {
"doctrine/common": "<3.2.2",
"doctrine/dbal": "<2.10",
"doctrine/orm": "<2.14.0",
"doctrine/orm": "<2.14.0 || 3.0.0",
"doctrine/mongodb-odm": "<2.4",
"doctrine/persistence": "<1.3",
"symfony/framework-bundle": "6.4.6 || 7.0.6",
Expand Down
233 changes: 233 additions & 0 deletions src/Doctrine/Orm/Filter/AbstractUuidFilter.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,233 @@
<?php

/*
* This file is part of the API Platform project.
*
* (c) Kévin Dunglas <dunglas@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/

declare(strict_types=1);

namespace ApiPlatform\Doctrine\Orm\Filter;

use ApiPlatform\Doctrine\Common\Filter\LoggerAwareInterface;
use ApiPlatform\Doctrine\Common\Filter\LoggerAwareTrait;
use ApiPlatform\Doctrine\Common\Filter\ManagerRegistryAwareInterface;
use ApiPlatform\Doctrine\Common\Filter\ManagerRegistryAwareTrait;
use ApiPlatform\Doctrine\Common\PropertyHelperTrait;
use ApiPlatform\Doctrine\Orm\PropertyHelperTrait as OrmPropertyHelperTrait;
use ApiPlatform\Doctrine\Orm\Util\QueryBuilderHelper;
use ApiPlatform\Doctrine\Orm\Util\QueryNameGeneratorInterface;
use ApiPlatform\Metadata\BackwardCompatibleFilterDescriptionTrait;
use ApiPlatform\Metadata\Exception\InvalidArgumentException;
use ApiPlatform\Metadata\JsonSchemaFilterInterface;
use ApiPlatform\Metadata\OpenApiParameterFilterInterface;
use ApiPlatform\Metadata\Operation;
use ApiPlatform\Metadata\Parameter;
use ApiPlatform\Metadata\QueryParameter;
use ApiPlatform\OpenApi\Model\Parameter as OpenApiParameter;
use Doctrine\DBAL\ArrayParameterType;
use Doctrine\DBAL\ParameterType;
use Doctrine\DBAL\Types\ConversionException;
use Doctrine\DBAL\Types\Type;
use Doctrine\ORM\Query\Expr\Join;
use Doctrine\ORM\QueryBuilder;

/**
* @internal
*/
class AbstractUuidFilter implements FilterInterface, ManagerRegistryAwareInterface, JsonSchemaFilterInterface, OpenApiParameterFilterInterface, LoggerAwareInterface
{
use BackwardCompatibleFilterDescriptionTrait;
use LoggerAwareTrait;
use ManagerRegistryAwareTrait;
use OrmPropertyHelperTrait;
use PropertyHelperTrait;

private const UUID_SCHEMA = [
'type' => 'string',
'format' => 'uuid',
];

public function apply(QueryBuilder $queryBuilder, QueryNameGeneratorInterface $queryNameGenerator, string $resourceClass, ?Operation $operation = null, array $context = []): void
{
$parameter = $context['parameter'] ?? null;
if (!$parameter) {
return;
}

$this->filterProperty($parameter->getProperty(), $parameter->getValue(), $queryBuilder, $queryNameGenerator, $resourceClass, $operation, $context);
}

private function filterProperty(string $property, mixed $value, QueryBuilder $queryBuilder, QueryNameGeneratorInterface $queryNameGenerator, string $resourceClass, ?Operation $operation = null, array $context = []): void
{
$alias = $queryBuilder->getRootAliases()[0];
$field = $property;

$associations = [];
if ($this->isPropertyNested($property, $resourceClass)) {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

At some point I'd like to share the relation filtering logic into other filters, I'm still wondering how we'd make this good enough.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'm really interested by the nested property filters soyuka so I would happy to help.
cf #7554 (comment) Currently I have a hack NestedFilter used this way

'target' => new QueryParameter(filter: new NestedFilter(new ExactFilter()), property: 'languagePair.target'),

but I think it would be awesome to support it natively.

Looking at your comments

I thought that you didn't want to support nested properties. So I'd like to understand what changed in this AbstractUuidFilter ? If it's supported for AbstractUuidFilter can it be for ExactFilter and PartialSearchFilter ? If not, why the bug you wanted to avoid on those filter cannot happen on this filter ?

Copy link
Member

@soyuka soyuka Jan 9, 2026

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

the bug is about the nested property not being of the type of the filter (main issue with the SearchFilter). We're working with @Maxcastel on providing the update for relations and nested props on all the filters. Can you show your NestedFilter ?

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We're working with @Maxcastel on providing the update for relations and nested props on all the filters.

I'm happy to hear it, don't hesitate to ping me on your discussion if I can help :)

Can you show your NestedFilter ?

I'm not sure my NestedFilter will help cause I think it's kinda hacky but I can still share it

    use OrmPropertyHelperTrait;
    use PropertyHelperTrait;

public function __construct(
        private readonly FilterInterface $filter,
    ) {
    }

    /**
     * @param array<string, mixed> $context
     */
    public function apply(QueryBuilder $queryBuilder, QueryNameGeneratorInterface $queryNameGenerator, string $resourceClass, ?Operation $operation = null, array $context = []): void
    {
        if ($this->filter instanceof ManagerRegistryAwareInterface) {
            $this->filter->setManagerRegistry($this->getManagerRegistry());
        }

        if ($this->filter instanceof LoggerAwareInterface) {
            $this->filter->setLogger($this->getLogger());
        }

        /** @var Parameter $parameter */
        $parameter = $context['parameter'];

        $property = $parameter->getProperty();
        if (null === $property) {
            throw new \InvalidArgumentException('Nested filter only supports single property.');
        }

        [$alias, $property] = $this->resolveNestedJoins(
            $queryBuilder,
            $queryNameGenerator,
            $property,
            $resourceClass,
        );

        $qb = clone $queryBuilder;
        $qb->resetDQLPart('from');
        $qb->from(self::class, $alias); // Override the root alias of the queryBuilder
        $qb->resetDQLPart('where');
        $qb->setParameters(new ArrayCollection());

        $newParameter = $parameter->withProperty($property)->withProperties([$property]);
        $this->filter->apply(
            $qb,
            $queryNameGenerator,
            $resourceClass,
            $operation,
            ['parameter' => $newParameter] + $context
        );

        $queryBuilder->andWhere($qb->getDQLPart('where'));
        $parameters = $queryBuilder->getParameters();

        foreach ($qb->getParameters() as $p) {
            $parameters->add($p);
        }

        $queryBuilder->setParameters($parameters);
    }

and then I'm using it with Filter which does not supports nested property, this way

'target' => new QueryParameter(filter: new NestedFilter(new ExactFilter()), property: 'languagePair.target'),

[$alias, $field, $associations] = $this->addJoinsForNestedProperty($property, $alias, $queryBuilder, $queryNameGenerator, $resourceClass, Join::INNER_JOIN);
}

$metadata = $this->getNestedMetadata($resourceClass, $associations);

if ($metadata->hasField($field)) {
$value = $this->convertValuesToTheDatabaseRepresentation($queryBuilder, $this->getDoctrineFieldType($property, $resourceClass), $value);
$this->addWhere($queryBuilder, $queryNameGenerator, $alias, $field, $value);

return;
}

// metadata doesn't have the field, nor an association on the field
if (!$metadata->hasAssociation($field)) {
$this->logger->notice('Tried to filter on a non-existent field or association', [
'field' => $field,
'resource_class' => $resourceClass,
'exception' => new InvalidArgumentException(\sprintf('Property "%s" does not exist in resource "%s".', $field, $resourceClass)),
]);

return;
}

// association, let's fetch the entity (or reference to it) if we can so we can make sure we get its orm id
$associationResourceClass = $metadata->getAssociationTargetClass($field);
$associationMetadata = $this->getClassMetadata($associationResourceClass);
$associationFieldIdentifier = $associationMetadata->getIdentifierFieldNames()[0];
$doctrineTypeField = $this->getDoctrineFieldType($associationFieldIdentifier, $associationResourceClass);

$associationAlias = $alias;
$associationField = $field;

if ($metadata->isCollectionValuedAssociation($associationField) || $metadata->isAssociationInverseSide($field)) {
$associationAlias = QueryBuilderHelper::addJoinOnce($queryBuilder, $queryNameGenerator, $alias, $associationField);
$associationField = $associationFieldIdentifier;
}

$value = $this->convertValuesToTheDatabaseRepresentation($queryBuilder, $doctrineTypeField, $value);
$this->addWhere($queryBuilder, $queryNameGenerator, $associationAlias, $associationField, $value);
}

/**
* Converts value to their database representation.
*/
private function convertValuesToTheDatabaseRepresentation(QueryBuilder $queryBuilder, ?string $doctrineFieldType, mixed $value): mixed
{
if (null === $doctrineFieldType || !Type::hasType($doctrineFieldType)) {
throw new InvalidArgumentException(\sprintf('The Doctrine type "%s" is not valid or not registered.', $doctrineFieldType));
}

$doctrineType = Type::getType($doctrineFieldType);
$platform = $queryBuilder->getEntityManager()->getConnection()->getDatabasePlatform();

$convertValue = static function (mixed $value) use ($doctrineType, $platform) {
try {
return $doctrineType->convertToDatabaseValue($value, $platform);
} catch (ConversionException $e) {
throw new InvalidArgumentException(\sprintf('The value "%s" could not be converted to database representation.', $value), previous: $e);
}
};

if (\is_array($value)) {
return array_map($convertValue, $value);
}

return $convertValue($value);
}

/**
* Adds where clause.
*/
private function addWhere(QueryBuilder $queryBuilder, QueryNameGeneratorInterface $queryNameGenerator, string $alias, string $field, mixed $value): void
{
$valueParameter = ':'.$queryNameGenerator->generateParameterName($field);
$aliasedField = \sprintf('%s.%s', $alias, $field);

if (!\is_array($value)) {
$queryBuilder
->andWhere($queryBuilder->expr()->eq($aliasedField, $valueParameter))
->setParameter($valueParameter, $value, $this->getDoctrineParameterType());

return;
}

$queryBuilder
->andWhere($queryBuilder->expr()->in($aliasedField, $valueParameter))
->setParameter($valueParameter, $value, $this->getDoctrineArrayParameterType());
}

protected function getDoctrineParameterType(): ?ParameterType
{
return null;
}

protected function getDoctrineArrayParameterType(): ?ArrayParameterType
{
return null;
}

public function getOpenApiParameters(Parameter $parameter): OpenApiParameter|array|null
{
$in = $parameter instanceof QueryParameter ? 'query' : 'header';
$schema = $parameter->getSchema();
$isArraySchema = 'array' === ($schema['type'] ?? null);
$hasNonArrayType = isset($schema['type']) && 'array' !== $schema['type'];

// Get filter's base schema
$baseSchema = self::UUID_SCHEMA;
$arraySchema = ['type' => 'array', 'items' => $baseSchema];

if ($isArraySchema) {
return new OpenApiParameter(
name: $parameter->getKey().'[]',
in: $in,
schema: $arraySchema,
style: 'deepObject',
explode: true,
);
}

if ($hasNonArrayType) {
return new OpenApiParameter(
name: $parameter->getKey(),
in: $in,
schema: $baseSchema,
);
}

// oneOf or no specific type constraint - return both with explicit schemas
return [
new OpenApiParameter(
name: $parameter->getKey(),
in: $in,
schema: $baseSchema,
),
new OpenApiParameter(
name: $parameter->getKey().'[]',
in: $in,
schema: $arraySchema,
style: 'deepObject',
explode: true,
),
];
}

public function getSchema(Parameter $parameter): array
{
if (false === $parameter->getCastToArray()) {
return self::UUID_SCHEMA;
}

return [
'oneOf' => [
self::UUID_SCHEMA,
[
'type' => 'array',
'items' => self::UUID_SCHEMA,
],
],
];
}
}
88 changes: 88 additions & 0 deletions src/Doctrine/Orm/Filter/UlidFilter.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,88 @@
<?php

/*
* This file is part of the API Platform project.
*
* (c) Kévin Dunglas <dunglas@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/

declare(strict_types=1);

namespace ApiPlatform\Doctrine\Orm\Filter;

use ApiPlatform\Metadata\Parameter;
use ApiPlatform\Metadata\QueryParameter;
use ApiPlatform\OpenApi\Model\Parameter as OpenApiParameter;

final class UlidFilter extends AbstractUuidFilter
{
private const ULID_SCHEMA = [
'type' => 'string',
'format' => 'ulid',
];

public function getOpenApiParameters(Parameter $parameter): OpenApiParameter|array
{
$in = $parameter instanceof QueryParameter ? 'query' : 'header';
$schema = $parameter->getSchema();
$isArraySchema = 'array' === ($schema['type'] ?? null);
$hasNonArrayType = isset($schema['type']) && 'array' !== $schema['type'];

$baseSchema = self::ULID_SCHEMA;
$arraySchema = ['type' => 'array', 'items' => $baseSchema];

if ($isArraySchema) {
return new OpenApiParameter(
name: $parameter->getKey().'[]',
in: $in,
schema: $arraySchema,
style: 'deepObject',
explode: true,
);
}

if ($hasNonArrayType) {
return new OpenApiParameter(
name: $parameter->getKey(),
in: $in,
schema: $baseSchema,
);
}

// oneOf or no specific type constraint - return both with explicit schemas
return [
new OpenApiParameter(
name: $parameter->getKey(),
in: $in,
schema: $baseSchema,
),
new OpenApiParameter(
name: $parameter->getKey().'[]',
in: $in,
schema: $arraySchema,
style: 'deepObject',
explode: true,
),
];
}

public function getSchema(Parameter $parameter): array
{
if (false === $parameter->getCastToArray()) {
return self::ULID_SCHEMA;
}

return [
'oneOf' => [
self::ULID_SCHEMA,
[
'type' => 'array',
'items' => self::ULID_SCHEMA,
],
],
];
}
}
40 changes: 40 additions & 0 deletions src/Doctrine/Orm/Filter/UuidBinaryFilter.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
<?php

/*
* This file is part of the API Platform project.
*
* (c) Kévin Dunglas <dunglas@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/

declare(strict_types=1);

namespace ApiPlatform\Doctrine\Orm\Filter;

use Composer\InstalledVersions;
use Composer\Semver\VersionParser;
use Doctrine\DBAL\ArrayParameterType;
use Doctrine\DBAL\ParameterType;

final class UuidBinaryFilter extends AbstractUuidFilter
{
public function __construct()
{
if (!InstalledVersions::satisfies(new VersionParser(), 'doctrine/orm', '^3.0.1')) {
// @see https://github.com/doctrine/orm/pull/11287
throw new \LogicException('The "doctrine/orm" package version 3.0.1 or higher is required to use the UuidBinaryFilter. Please upgrade your dependencies.');
}
}

protected function getDoctrineParameterType(): ParameterType
{
return ParameterType::BINARY;
}

protected function getDoctrineArrayParameterType(): ArrayParameterType
{
return ArrayParameterType::BINARY;
}
}
18 changes: 18 additions & 0 deletions src/Doctrine/Orm/Filter/UuidFilter.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
<?php

/*
* This file is part of the API Platform project.
*
* (c) Kévin Dunglas <dunglas@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/

declare(strict_types=1);

namespace ApiPlatform\Doctrine\Orm\Filter;

final class UuidFilter extends AbstractUuidFilter
{
}
Loading
Loading