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

/*
* This file is part of the API Platform project.
*
* (c) Kévin Dunglas <[email protected]>
*
* 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\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);
}

protected function filterProperty(string $property, mixed $value, QueryBuilder $queryBuilder, QueryNameGeneratorInterface $queryNameGenerator, string $resourceClass, ?Operation $operation = null, array $context = []): void
Copy link
Member

Choose a reason for hiding this comment

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

does this really need to be protected? I'd prefer if it wasn't.

{
$alias = $queryBuilder->getRootAliases()[0];
$field = $property;

$values = (array) $value;
$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)) {
return;
Copy link
Member

Choose a reason for hiding this comment

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

currently we log when something goes wrong, maybe add a log information here as the filter looks not valid?

}

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

/**
* Converts values to their database representation.
*/
private function convertValuesToTheDatabaseRepresentationIfNecessary(QueryBuilder $queryBuilder, ?string $doctrineFieldType, array $values): array
{
if ($doctrineFieldType && Type::hasType($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;
}

return $values;
Copy link
Member

Choose a reason for hiding this comment

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

we should not need this this is done by Doctrine when applying parameters no? If this is really needed could you tell me why? Also you could have a guard clause in the callee and reduce the function complexity.

}

/**
* Adds where clause.
*/
private function addWhere(QueryBuilder $queryBuilder, QueryNameGeneratorInterface $queryNameGenerator, string $alias, string $field, mixed $values): void
{
if (!\is_array($values)) {
$values = [$values];
}
Comment on lines +139 to +141
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 (!\is_array($values)) {
$values = [$values];
}

Type casting is done before reaching the filter (see Parameter::castToArray).


$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 +146 to +152
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;
}


$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 <[email protected]>
*
* 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;
}
}
30 changes: 30 additions & 0 deletions src/Doctrine/Orm/Filter/UuidBinaryFilter.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
<?php

/*
* This file is part of the API Platform project.
*
* (c) Kévin Dunglas <[email protected]>
*
* 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 Doctrine\DBAL\ArrayParameterType;
use Doctrine\DBAL\ParameterType;

final class UuidBinaryFilter extends AbstractUuidFilter
{
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 <[email protected]>
*
* 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

},
"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
48 changes: 48 additions & 0 deletions tests/Fixtures/TestBundle/Entity/Uuid/RamseyUuidBinaryDevice.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
<?php

/*
* This file is part of the API Platform project.
*
* (c) Kévin Dunglas <[email protected]>
*
* 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\Tests\Fixtures\TestBundle\Entity\Uuid;

use ApiPlatform\Doctrine\Orm\Filter\UuidBinaryFilter;
use ApiPlatform\Metadata\ApiResource;
use ApiPlatform\Metadata\Get;
use ApiPlatform\Metadata\GetCollection;
use ApiPlatform\Metadata\Post;
use ApiPlatform\Metadata\QueryParameter;
use Doctrine\ORM\Mapping as ORM;
use Ramsey\Uuid\Uuid;
use Ramsey\Uuid\UuidInterface;

#[ApiResource(operations: [
new Get(),
new GetCollection(
parameters: [
'id' => new QueryParameter(
filter: new UuidBinaryFilter(),
),
]
),
new Post(),
])]
#[ORM\Entity]
class RamseyUuidBinaryDevice
{
#[ORM\Id]
#[ORM\Column(type: 'uuid_binary', unique: true)]
public UuidInterface $id;

public function __construct(?UuidInterface $id = null)
{
$this->id = $id ?? Uuid::uuid7();
}
}
Loading
Loading