-
-
Notifications
You must be signed in to change notification settings - Fork 958
feat(doctrine): uuid filter #7628
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
+1,669
−3
Merged
Changes from all commits
Commits
Show all changes
4 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Some comments aren't visible on the classic Files Changed page.
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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)) { | ||
| [$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; | ||
soyuka marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| } | ||
|
|
||
| // 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); | ||
soyuka marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| $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, | ||
| ], | ||
| ], | ||
| ]; | ||
| } | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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, | ||
| ], | ||
| ], | ||
| ]; | ||
| } | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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; | ||
| } | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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 | ||
| { | ||
| } |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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
NestedFilterused this waybut 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 ?
Uh oh!
There was an error while loading. Please reload this page.
There was a problem hiding this comment.
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?There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I'm happy to hear it, don't hesitate to ping me on your discussion if I can help :)
I'm not sure my NestedFilter will help cause I think it's kinda hacky but I can still share it
and then I'm using it with Filter which does not supports nested property, this way