Skip to content
Merged
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
31 changes: 31 additions & 0 deletions src/Doctrine/Common/Filter/DateFilterTrait.php
Original file line number Diff line number Diff line change
Expand Up @@ -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);
}
}
15 changes: 7 additions & 8 deletions src/Doctrine/Odm/Filter/DateFilter.php
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@
*
* Syntax: `?property[<after|before|strictly_after|strictly_before>]=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.
*
Expand Down Expand Up @@ -150,7 +150,7 @@ final class DateFilter implements DateFilterInterface, FilterInterface, JsonSche
/**
* @param array<string, mixed>|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();
Expand Down Expand Up @@ -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;
Expand Down Expand Up @@ -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
Expand Down
2 changes: 1 addition & 1 deletion src/Doctrine/Odm/composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@
],
"require": {
"php": ">=8.2",
"api-platform/doctrine-common": "^5.0.4",
"api-platform/doctrine-common": "^5.1",
"api-platform/metadata": "^5.0",
"api-platform/serializer": "^5.0",
"api-platform/state": "^5.0",
Expand Down
15 changes: 7 additions & 8 deletions src/Doctrine/Orm/Filter/DateFilter.php
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,7 @@
*
* Syntax: `?property[<after|before|strictly_after|strictly_before>]=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.
*
Expand Down Expand Up @@ -169,7 +169,7 @@ final class DateFilter implements DateFilterInterface, FilterInterface, JsonSche
/**
* @param array<string, mixed>|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();
Expand Down Expand Up @@ -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;
Expand Down Expand Up @@ -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
Expand Down
2 changes: 1 addition & 1 deletion src/Doctrine/Orm/composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@
],
"require": {
"php": ">=8.2",
"api-platform/doctrine-common": "^5.0.4",
"api-platform/doctrine-common": "^5.1",
"api-platform/metadata": "^5.0",
"api-platform/serializer": "^5.0",
"api-platform/state": "^5.0",
Expand Down
4 changes: 4 additions & 0 deletions tests/Fixtures/TestBundle/Document/FilteredDateParameter.php
Original file line number Diff line number Diff line change
Expand Up @@ -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',
Expand Down
4 changes: 4 additions & 0 deletions tests/Fixtures/TestBundle/Entity/FilteredDateParameter.php
Original file line number Diff line number Diff line change
Expand Up @@ -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',
Expand Down
19 changes: 19 additions & 0 deletions tests/Functional/Parameters/DateFilterTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
Loading