Skip to content
Open
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
203 changes: 203 additions & 0 deletions src/Doctrine/Orm/Filter/AbstractUuidFilter.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,203 @@
<?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;

$values = (array) $value;
Copy link
Member

Choose a reason for hiding this comment

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

Is it possible not to cast this?

$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.

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

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

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

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;
}

$values = $this->convertValuesToTheDatabaseRepresentationIfNecessary($queryBuilder, $doctrineTypeField, $values);
$this->addWhere($queryBuilder, $queryNameGenerator, $associationAlias, $associationField, $values);
Copy link
Member

Choose a reason for hiding this comment

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

Suggested change
$this->addWhere($queryBuilder, $queryNameGenerator, $associationAlias, $associationField, $values);
if ($values) {
$this->addWhere($queryBuilder, $queryNameGenerator, $associationAlias, $associationField, $values);
}

}

/**
* Converts values to their database representation.
*/
private function convertValuesToTheDatabaseRepresentationIfNecessary(QueryBuilder $queryBuilder, ?string $doctrineFieldType, array $values): array
{
if (null === $doctrineFieldType || !Type::hasType($doctrineFieldType)) {
throw new \LogicException(\sprintf('The Doctrine type "%s" is not valid or not registered.', $doctrineFieldType));
Copy link
Member

Choose a reason for hiding this comment

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

Suggested change
throw new \LogicException(\sprintf('The Doctrine type "%s" is not valid or not registered.', $doctrineFieldType));
throw new InvalidArgumentException(\sprintf('The Doctrine type "%s" is not valid or not registered.', $doctrineFieldType));

from api platform's namespace

}

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

foreach ($values as $value) {
try {
$databaseValues[] = $doctrineType->convertToDatabaseValue($value, $platform);
} catch (ConversionException $e) {
$this->logger->notice('Invalid value conversion value to its database representation', [
'exception' => $e,
]);
$databaseValues[] = null;
Copy link
Member

Choose a reason for hiding this comment

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

Suggested change
$databaseValues[] = null;

}
}

return $databaseValues;
}
Comment on lines +117 to +139
Copy link
Member

Choose a reason for hiding this comment

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

Suggested change
private function convertValuesToTheDatabaseRepresentationIfNecessary(QueryBuilder $queryBuilder, ?string $doctrineFieldType, array $values): array
{
if (null === $doctrineFieldType || !Type::hasType($doctrineFieldType)) {
throw new \LogicException(\sprintf('The Doctrine type "%s" is not valid or not registered.', $doctrineFieldType));
}
$doctrineType = Type::getType($doctrineFieldType);
$platform = $queryBuilder->getEntityManager()->getConnection()->getDatabasePlatform();
$databaseValues = [];
foreach ($values as $value) {
try {
$databaseValues[] = $doctrineType->convertToDatabaseValue($value, $platform);
} catch (ConversionException $e) {
$this->logger->notice('Invalid value conversion value to its database representation', [
'exception' => $e,
]);
$databaseValues[] = null;
}
}
return $databaseValues;
}
private function convertToDatabaseValue(QueryBuilder $queryBuilder, ?string $doctrineFieldType, mixed $value): array
{
if (null === $doctrineFieldType || !Type::hasType($doctrineFieldType)) {
throw new RuntimeException(\sprintf('The Doctrine type "%s" is not valid or not registered.', $doctrineFieldType));
}
$doctrineType = Type::getType($doctrineFieldType);
$platform = $queryBuilder->getEntityManager()->getConnection()->getDatabasePlatform();
$databaseValues = [];
if (\is_array($value)) {
$databaseValues = [];
foreach ($value as $val) {
try {
$databaseValues[] = $doctrineType->convertToDatabaseValue($val, $platform);
} catch (ConversionException $e) {
$this->logger->notice('Invalid value conversion to database representation', [
'exception' => $e,
]);
}
}
return $databaseValues;
}
try {
return $doctrineType->convertToDatabaseValue($value, $platform);
} catch (ConversionException $e) {
$this->logger->notice('Invalid value conversion to database representation', [
'exception' => $e,
]);
return null;
}
return $databaseValues;
}


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

if (1 === \count($values)) {
$queryBuilder
->andWhere($queryBuilder->expr()->eq($aliasedField, $valueParameter))
->setParameter($valueParameter, $values[0], $this->getDoctrineParameterType());

return;
}
Comment on lines +149 to +155
Copy link
Member

Choose a reason for hiding this comment

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

Suggested change
if (1 === \count($values)) {
$queryBuilder
->andWhere($queryBuilder->expr()->eq($aliasedField, $valueParameter))
->setParameter($valueParameter, $values[0], $this->getDoctrineParameterType());
return;
}
if (!is_array($values)) {
$queryBuilder
->andWhere($queryBuilder->expr()->eq($aliasedField, $valueParameter))
->setParameter($valueParameter, $values[0], $this->getDoctrineParameterType());
return;
}

Copy link
Contributor Author

Choose a reason for hiding this comment

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


$queryBuilder
->andWhere($queryBuilder->expr()->in($aliasedField, $valueParameter))
->setParameter($valueParameter, $values, $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();

return [
new OpenApiParameter(
name: $key,
in: $in,
schema: self::UUID_SCHEMA,
style: 'form',
explode: false
),
new OpenApiParameter(
name: $key.'[]',
in: $in,
description: 'One or more Uuids',
schema: [
'type' => 'array',
'items' => self::UUID_SCHEMA,
],
style: 'deepObject',
explode: true
),
];
}

public function getSchema(Parameter $parameter): array
{
return self::UUID_SCHEMA;
Copy link
Contributor Author

Choose a reason for hiding this comment

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

API Platform not automatically adds a Symfony Uuid/Ulid constraint, I could create another PR for that

Copy link
Member

Choose a reason for hiding this comment

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

}
}
58 changes: 58 additions & 0 deletions src/Doctrine/Orm/Filter/UlidFilter.php
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;
}
}
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
{
}
2 changes: 1 addition & 1 deletion src/Doctrine/Orm/composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Copy link
Contributor Author

Choose a reason for hiding this comment

The 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 ?

Copy link
Member

Choose a reason for hiding this comment

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

yes totally

Copy link
Contributor Author

Choose a reason for hiding this comment

The 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
https://github.com/api-platform/core/blob/4.2/composer.json#L129C10-L129C33 and doctrine v2 is not compatible with doctrine dbal v4

},
"require-dev": {
"doctrine/doctrine-bundle": "^2.11 || ^3.1",
Expand Down
9 changes: 9 additions & 0 deletions src/Symfony/Bundle/Resources/config/doctrine_orm.php
Original file line number Diff line number Diff line change
Expand Up @@ -222,6 +222,15 @@
->parent('api_platform.doctrine.orm.search_filter')
->args([[]]);

$services->set('api_platform.doctrine.orm.uuid_filter', 'ApiPlatform\Doctrine\Orm\Filter\UuidFilter');
$services->alias('ApiPlatform\Doctrine\Orm\Filter\UuidFilter', 'api_platform.doctrine.orm.uuid_filter');

$services->set('api_platform.doctrine.orm.ulid_filter', 'ApiPlatform\Doctrine\Orm\Filter\UlidFilter');
$services->alias('ApiPlatform\Doctrine\Orm\Filter\UlidFilter', 'api_platform.doctrine.orm.ulid_filter');

$services->set('api_platform.doctrine.orm.uuid_binary_filter', 'ApiPlatform\Doctrine\Orm\Filter\UuidBinaryFilter');
$services->alias('ApiPlatform\Doctrine\Orm\Filter\UuidBinaryFilter', 'api_platform.doctrine.orm.uuid_binary_filter');

$services->set('api_platform.doctrine.orm.metadata.resource.metadata_collection_factory', 'ApiPlatform\Doctrine\Orm\Metadata\Resource\DoctrineOrmResourceCollectionMetadataFactory')
->decorate('api_platform.metadata.resource.metadata_collection_factory', null, 40)
->args([
Expand Down
Loading
Loading