Skip to content

Commit

Permalink
Normalize date time value filter
Browse files Browse the repository at this point in the history
  • Loading branch information
vuongxuongminh committed Dec 3, 2020
1 parent e2262c0 commit b9e32de
Show file tree
Hide file tree
Showing 3 changed files with 31 additions and 2 deletions.
17 changes: 17 additions & 0 deletions src/Bridge/Doctrine/Common/Filter/DateFilterTrait.php
Expand Up @@ -14,6 +14,7 @@
namespace ApiPlatform\Core\Bridge\Doctrine\Common\Filter;

use ApiPlatform\Core\Bridge\Doctrine\Common\PropertyHelperTrait;
use ApiPlatform\Core\Exception\InvalidArgumentException;

/**
* Trait for filtering the collection by date intervals.
Expand Down Expand Up @@ -79,4 +80,20 @@ protected function getFilterDescription(string $property, string $period): array
],
];
}

/**
* Normalize the value.
*/
private function normalizeValue($value, string $operator): ?string
{
if (!\is_string($value)) {
$this->getLogger()->notice('Invalid filter ignored', [
'exception' => new InvalidArgumentException(sprintf('Invalid value for "[%s]", expected string', $operator)),
]);

return null;
}

return $value;
}
}
8 changes: 7 additions & 1 deletion src/Bridge/Doctrine/MongoDbOdm/Filter/DateFilter.php
Expand Up @@ -109,9 +109,15 @@ protected function filterProperty(string $property, $values, Builder $aggregatio
*/
private function addMatch(Builder $aggregationBuilder, string $field, string $operator, $value, string $nullManagement = null): void
{
$value = $this->normalizeValue($value, $operator);

if (null === $value) {
return;
}

try {
$value = new \DateTime($value);
} catch (\Throwable $e) {
} catch (\Exception $e) {
// Silently ignore this filter if it can not be transformed to a \DateTime
$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)),
Expand Down
8 changes: 7 additions & 1 deletion src/Bridge/Doctrine/Orm/Filter/DateFilter.php
Expand Up @@ -131,9 +131,15 @@ protected function filterProperty(string $property, $values, QueryBuilder $query
protected function addWhere(QueryBuilder $queryBuilder, QueryNameGeneratorInterface $queryNameGenerator, string $alias, string $field, string $operator, $value, string $nullManagement = null, $type = null)
{
$type = (string) $type;
$value = $this->normalizeValue($value, $operator);

if (null === $value) {
return;
}

try {
$value = false === strpos($type, '_immutable') ? new \DateTime($value) : new \DateTimeImmutable($value);
} catch (\Throwable $e) {
} catch (\Exception $e) {
// Silently ignore this filter if it can not be transformed to a \DateTime
$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)),
Expand Down

0 comments on commit b9e32de

Please sign in to comment.