From a2523734118ab7b9aa8113e492a285780136e76c Mon Sep 17 00:00:00 2001 From: soyuka Date: Tue, 13 Oct 2026 15:41:31 +0200 Subject: [PATCH 1/2] feat(doctrine): add an input format to DateFilter Parse the query value with createFromFormat when a format is set, e.g. new DateFilter(format: 'd/m/Y'), on ORM and ODM. Unparsed fields reset to zero and overflowing dates are ignored. Closes #8047 --- .../Common/Filter/DateFilterTrait.php | 31 +++++++++++++++++++ src/Doctrine/Odm/Filter/DateFilter.php | 13 ++++---- src/Doctrine/Orm/Filter/DateFilter.php | 13 ++++---- .../Document/FilteredDateParameter.php | 4 +++ .../Entity/FilteredDateParameter.php | 4 +++ .../Functional/Parameters/DateFilterTest.php | 19 ++++++++++++ 6 files changed, 70 insertions(+), 14 deletions(-) diff --git a/src/Doctrine/Common/Filter/DateFilterTrait.php b/src/Doctrine/Common/Filter/DateFilterTrait.php index 4485e94881a..11bbb27cb2f 100644 --- a/src/Doctrine/Common/Filter/DateFilterTrait.php +++ b/src/Doctrine/Common/Filter/DateFilterTrait.php @@ -101,4 +101,35 @@ private function normalizeValue(mixed $value, string $operator): ?string return $value; } + + private function createDateFromValue(string $value, bool $immutable, ?string $format): ?\DateTimeInterface + { + if (null === $format) { + try { + return $immutable ? new \DateTimeImmutable($value) : new \DateTime($value); + } catch (\Exception) { + return null; + } + } + + // "!" resets unparsed fields to the epoch, otherwise they take the current time + $pattern = str_starts_with($format, '!') || str_contains($format, '|') ? $format : '!'.$format; + $date = $immutable ? \DateTimeImmutable::createFromFormat($pattern, $value) : \DateTime::createFromFormat($pattern, $value); + $errors = \DateTimeImmutable::getLastErrors(); + + if (false === $date || (false !== $errors && ($errors['warning_count'] > 0 || $errors['error_count'] > 0))) { + return null; + } + + return $date; + } + + private function getInvalidDateMessage(string $field, ?string $format): string + { + if (null === $format) { + return \sprintf('The field "%s" has a wrong date format. Use one accepted by the \DateTime constructor', $field); + } + + return \sprintf('The field "%s" has a wrong date format. Expected format "%s"', $field, $format); + } } diff --git a/src/Doctrine/Odm/Filter/DateFilter.php b/src/Doctrine/Odm/Filter/DateFilter.php index 97294a7d860..fc2b707b767 100644 --- a/src/Doctrine/Odm/Filter/DateFilter.php +++ b/src/Doctrine/Odm/Filter/DateFilter.php @@ -150,7 +150,7 @@ final class DateFilter implements DateFilterInterface, FilterInterface, JsonSche /** * @param array|null $properties */ - public function __construct(?ManagerRegistry $managerRegistry = null, ?LoggerInterface $logger = null, ?array $properties = null, ?NameConverterInterface $nameConverter = null) + public function __construct(?ManagerRegistry $managerRegistry = null, ?LoggerInterface $logger = null, ?array $properties = null, ?NameConverterInterface $nameConverter = null, private readonly ?string $format = null) { $this->managerRegistry = $managerRegistry; $this->logger = $logger ?? new NullLogger(); @@ -261,12 +261,11 @@ private function addMatch(Builder $aggregationBuilder, string $field, string $op return; } - try { - $value = new \DateTime($value); - } catch (\Exception) { - // Silently ignore this filter if it can not be transformed to a \DateTime + $value = $this->createDateFromValue($value, false, $this->format); + + if (null === $value) { $this->logger->notice('Invalid filter ignored', [ - 'exception' => new InvalidArgumentException(\sprintf('The field "%s" has a wrong date format. Use one accepted by the \DateTime constructor', $field)), + 'exception' => new InvalidArgumentException($this->getInvalidDateMessage($field, $this->format)), ]); return; @@ -299,7 +298,7 @@ private function addMatch(Builder $aggregationBuilder, string $field, string $op */ public function getSchema(Parameter $parameter): array { - return ['type' => 'string', 'format' => 'date']; + return null === $this->format ? ['type' => 'string', 'format' => 'date'] : ['type' => 'string']; } public function getOpenApiParameters(Parameter $parameter): array diff --git a/src/Doctrine/Orm/Filter/DateFilter.php b/src/Doctrine/Orm/Filter/DateFilter.php index 1632645eabc..e309b23fb09 100644 --- a/src/Doctrine/Orm/Filter/DateFilter.php +++ b/src/Doctrine/Orm/Filter/DateFilter.php @@ -169,7 +169,7 @@ final class DateFilter implements DateFilterInterface, FilterInterface, JsonSche /** * @param array|null $properties */ - public function __construct(?ManagerRegistry $managerRegistry = null, ?LoggerInterface $logger = null, ?array $properties = null, ?NameConverterInterface $nameConverter = null) + public function __construct(?ManagerRegistry $managerRegistry = null, ?LoggerInterface $logger = null, ?array $properties = null, ?NameConverterInterface $nameConverter = null, private readonly ?string $format = null) { $this->managerRegistry = $managerRegistry; $this->logger = $logger ?? new NullLogger(); @@ -330,12 +330,11 @@ protected function addWhere(QueryBuilder $queryBuilder, QueryNameGeneratorInterf return; } - try { - $value = !str_contains($type, '_immutable') ? new \DateTime($value) : new \DateTimeImmutable($value); - } catch (\Exception) { - // Silently ignore this filter if it can not be transformed to a \DateTime + $value = $this->createDateFromValue($value, str_contains($type, '_immutable'), $this->format); + + if (null === $value) { $this->logger->notice('Invalid filter ignored', [ - 'exception' => new InvalidArgumentException(\sprintf('The field "%s" has a wrong date format. Use one accepted by the \DateTime constructor', $field)), + 'exception' => new InvalidArgumentException($this->getInvalidDateMessage($field, $this->format)), ]); return; @@ -376,7 +375,7 @@ protected function addWhere(QueryBuilder $queryBuilder, QueryNameGeneratorInterf */ public function getSchema(Parameter $parameter): array { - return ['type' => 'string', 'format' => 'date']; + return null === $this->format ? ['type' => 'string', 'format' => 'date'] : ['type' => 'string']; } public function getOpenApiParameters(Parameter $parameter): array diff --git a/tests/Fixtures/TestBundle/Document/FilteredDateParameter.php b/tests/Fixtures/TestBundle/Document/FilteredDateParameter.php index e7c7a9be5ea..7c829ede63a 100644 --- a/tests/Fixtures/TestBundle/Document/FilteredDateParameter.php +++ b/tests/Fixtures/TestBundle/Document/FilteredDateParameter.php @@ -47,6 +47,10 @@ property: 'createdAt', openApi: new Parameter('date_old_way', 'query', allowEmptyValue: true) ), + 'createdAtFormatted' => new QueryParameter( + filter: new DateFilter(format: 'd/m/Y'), + property: 'createdAt', + ), 'createdAtComparison' => new QueryParameter( filter: new ComparisonFilter(new ExactFilter()), property: 'createdAt', diff --git a/tests/Fixtures/TestBundle/Entity/FilteredDateParameter.php b/tests/Fixtures/TestBundle/Entity/FilteredDateParameter.php index 97786fe1330..8180ddea754 100644 --- a/tests/Fixtures/TestBundle/Entity/FilteredDateParameter.php +++ b/tests/Fixtures/TestBundle/Entity/FilteredDateParameter.php @@ -47,6 +47,10 @@ property: 'createdAt', openApi: new Parameter('date_old_way', 'query', allowEmptyValue: true) ), + 'createdAtFormatted' => new QueryParameter( + filter: new DateFilter(format: 'd/m/Y'), + property: 'createdAt', + ), 'createdAtComparison' => new QueryParameter( filter: new ComparisonFilter(new ExactFilter()), property: 'createdAt', diff --git a/tests/Functional/Parameters/DateFilterTest.php b/tests/Functional/Parameters/DateFilterTest.php index 9d3e9b40c56..db81508b010 100644 --- a/tests/Functional/Parameters/DateFilterTest.php +++ b/tests/Functional/Parameters/DateFilterTest.php @@ -119,6 +119,25 @@ public static function dateFilterNullAndEmptyScenariosProvider(): \Generator yield 'date__alias_old_way_with_empty_alias' => ['/filtered_date_parameters?date_old_way=', 4]; } + public function testDateFilterWithInputFormat(): void + { + $client = self::createClient(); + + $items = $client->request('GET', '/filtered_date_parameters?createdAtFormatted[before]=15/06/2024')->toArray()['hydra:member']; + $this->assertCount(2, $items); + $this->assertSame(['2024-01-01', '2024-06-15'], array_map(static fn (array $item): string => substr($item['createdAt'], 0, 10), $items)); + + $items = $client->request('GET', '/filtered_date_parameters?createdAtFormatted[strictly_before]=15/06/2024')->toArray()['hydra:member']; + $this->assertCount(1, $items); + $this->assertSame('2024-01-01', substr($items[0]['createdAt'], 0, 10)); + + $items = $client->request('GET', '/filtered_date_parameters?createdAtFormatted[after]=15/06/2024')->toArray()['hydra:member']; + $this->assertCount(2, $items); + + $this->assertCount(4, $client->request('GET', '/filtered_date_parameters?createdAtFormatted[before]=2024-06-15')->toArray()['hydra:member']); + $this->assertCount(4, $client->request('GET', '/filtered_date_parameters?createdAtFormatted[before]=32/03/2024')->toArray()['hydra:member']); + } + /** * @throws \Throwable * @throws MongoDBException From 859d8c74a42daa3170a485e245b395bfb164d720 Mon Sep 17 00:00:00 2001 From: soyuka Date: Fri, 16 Oct 2026 11:04:14 +0200 Subject: [PATCH 2/2] chore(doctrine): require doctrine-common ^5.1 for DateFilter format --- src/Doctrine/Odm/Filter/DateFilter.php | 2 +- src/Doctrine/Odm/composer.json | 2 +- src/Doctrine/Orm/Filter/DateFilter.php | 2 +- src/Doctrine/Orm/composer.json | 2 +- 4 files changed, 4 insertions(+), 4 deletions(-) diff --git a/src/Doctrine/Odm/Filter/DateFilter.php b/src/Doctrine/Odm/Filter/DateFilter.php index fc2b707b767..ee3019128f5 100644 --- a/src/Doctrine/Odm/Filter/DateFilter.php +++ b/src/Doctrine/Odm/Filter/DateFilter.php @@ -40,7 +40,7 @@ * * Syntax: `?property[]=value`. * - * The value can take any date format supported by the [`\DateTime` constructor](https://www.php.net/manual/en/datetime.construct.php). + * The value can take any date format supported by the [`\DateTime` constructor](https://www.php.net/manual/en/datetime.construct.php), or, when the `format` argument is set, the format given to `DateTimeImmutable::createFromFormat()`. * * The `after` and `before` filters will filter including the value whereas `strictly_after` and `strictly_before` will filter excluding the value. * diff --git a/src/Doctrine/Odm/composer.json b/src/Doctrine/Odm/composer.json index cbf9dd53216..1f0de46af49 100644 --- a/src/Doctrine/Odm/composer.json +++ b/src/Doctrine/Odm/composer.json @@ -25,7 +25,7 @@ ], "require": { "php": ">=8.2", - "api-platform/doctrine-common": "^5.0", + "api-platform/doctrine-common": "^5.1", "api-platform/metadata": "^5.0", "api-platform/serializer": "^5.0", "api-platform/state": "^5.0", diff --git a/src/Doctrine/Orm/Filter/DateFilter.php b/src/Doctrine/Orm/Filter/DateFilter.php index e309b23fb09..fac57456f3b 100644 --- a/src/Doctrine/Orm/Filter/DateFilter.php +++ b/src/Doctrine/Orm/Filter/DateFilter.php @@ -47,7 +47,7 @@ * * Syntax: `?property[]=value`. * - * The value can take any date format supported by the [`\DateTime` constructor](https://www.php.net/manual/en/datetime.construct.php). + * The value can take any date format supported by the [`\DateTime` constructor](https://www.php.net/manual/en/datetime.construct.php), or, when the `format` argument is set, the format given to `DateTimeImmutable::createFromFormat()`. * * The `after` and `before` filters will filter including the value whereas `strictly_after` and `strictly_before` will filter excluding the value. * diff --git a/src/Doctrine/Orm/composer.json b/src/Doctrine/Orm/composer.json index fc555709c53..cfeb09c682e 100644 --- a/src/Doctrine/Orm/composer.json +++ b/src/Doctrine/Orm/composer.json @@ -24,7 +24,7 @@ ], "require": { "php": ">=8.2", - "api-platform/doctrine-common": "^5.0", + "api-platform/doctrine-common": "^5.1", "api-platform/metadata": "^5.0", "api-platform/serializer": "^5.0", "api-platform/state": "^5.0",