-
-
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
base: main
Are you sure you want to change the base?
Changes from all commits
3f409a9
3719b08
42b759e
860bbed
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,238 @@ | ||
| <?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); | ||
|
Member
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. let's catch the InvalidArgumentException and log in here so that we never call
Contributor
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. This doesn't seem ok to me because in the case, we will fetch all the items. Is it really necessary to catch the exception and log ? Or, do you want also to rethrow the exception ? |
||
| $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): array | ||
| { | ||
| $in = $parameter instanceof QueryParameter ? 'query' : 'header'; | ||
| $key = $parameter->getKey(); | ||
| $schema = $parameter->getSchema(); | ||
| $addStringParam = false; | ||
| $addArrayParam = false; | ||
| $openApiParameters = []; | ||
|
|
||
| if (null === $schema) { | ||
| $addStringParam = true; | ||
| $addArrayParam = true; | ||
| } | ||
|
|
||
| foreach ($schema['oneOf'] ?? [$schema] as $item) { | ||
| if (!isset($item['type']) || 'string' === $item['type']) { | ||
| $addStringParam = true; | ||
| } | ||
|
|
||
| if (!isset($item['type']) || 'array' === $item['type']) { | ||
| $addArrayParam = true; | ||
| } | ||
| } | ||
|
|
||
| if ($addStringParam) { | ||
| $openApiParameters[] = new OpenApiParameter( | ||
| name: $key, | ||
| in: $in, | ||
| schema: self::UUID_SCHEMA, | ||
| style: 'form', | ||
| explode: false | ||
| ); | ||
| } | ||
|
|
||
| if ($addArrayParam) { | ||
| $openApiParameters[] = new OpenApiParameter( | ||
| name: $key.'[]', | ||
| in: $in, | ||
| description: 'One or more Uuids', | ||
| schema: [ | ||
| 'type' => 'array', | ||
| 'items' => self::UUID_SCHEMA, | ||
| ], | ||
| style: 'deepObject', | ||
| explode: true | ||
| ); | ||
| } | ||
|
|
||
| return $openApiParameters; | ||
| } | ||
|
|
||
| public function getSchema(Parameter $parameter): array | ||
| { | ||
| if (null !== $parameter->getSchema()) { | ||
| return $parameter->getSchema(); | ||
| } | ||
|
|
||
| return [ | ||
| 'oneOf' => [ | ||
| self::UUID_SCHEMA, | ||
| [ | ||
| 'type' => 'array', | ||
| 'items' => self::UUID_SCHEMA, | ||
| ], | ||
| ], | ||
| ]; | ||
| } | ||
| } | ||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,58 @@ | ||
| <?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): array | ||
| { | ||
| $in = $parameter instanceof QueryParameter ? 'query' : 'header'; | ||
| $key = $parameter->getKey(); | ||
|
|
||
| return [ | ||
| new OpenApiParameter( | ||
| name: $key, | ||
| in: $in, | ||
| schema: self::ULID_SCHEMA, | ||
| style: 'form', | ||
| explode: false | ||
| ), | ||
| new OpenApiParameter( | ||
| name: $key.'[]', | ||
| in: $in, | ||
| description: 'One or more Ulids', | ||
| schema: [ | ||
| 'type' => 'array', | ||
| 'items' => self::ULID_SCHEMA, | ||
| ], | ||
| style: 'deepObject', | ||
| explode: true | ||
| ), | ||
| ]; | ||
| } | ||
|
|
||
| public function getSchema(Parameter $parameter): array | ||
| { | ||
| return self::ULID_SCHEMA; | ||
| } | ||
| } |
| 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; | ||
| } | ||
| } |
| 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 | ||
| { | ||
| } |
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -27,7 +27,7 @@ | |
| "api-platform/doctrine-common": "^4.2.9", | ||
| "api-platform/metadata": "^4.2", | ||
| "api-platform/state": "^4.2.4", | ||
| "doctrine/orm": "^2.17 || ^3.0" | ||
| "doctrine/orm": "^2.17 || ^3.0.1" | ||
|
Contributor
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. It needs allowing ArrayParameterType for uuid binary in QueryBuilder doctrine/orm#11287. So, Uuid binary filter does not work with Doctrine 2.x. Can I skip the tests if Doctrine 2.x is installed and throws an exception in the UuidBianryFilter ?
Member
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. yes totally
Contributor
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. The build was successful previously because Doctrine v3 was installed in the Symfony lowest step. Maybe, because doctrine/dbal": "^4.0" is required |
||
| }, | ||
| "require-dev": { | ||
| "doctrine/doctrine-bundle": "^2.11 || ^3.1", | ||
|
|
||
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.