Skip to content

[Validator] Format datetime values in comparison constraints with dateFormat option #39857

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 2 commits into from
Closed
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
14 changes: 14 additions & 0 deletions src/Symfony/Component/Validator/CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,20 @@
CHANGELOG
=========

5.4
---

* Add a `dateFormat` option to comparison constraints (`EqualTo`,
`GreaterThanOrEqual`, `GreaterThan`, `LessThanOrEqual`, `LessThan`,
`IndenticalTo`, `NotEqualTo` and `NotIdenticalTo`) to format datetimes in
placeholders:
```php
/**
* @Assert\EqualTo(value="2020-01-01", dateFormat="Y-d-m")
*/
```
will output a message like: `This value should be equal to 2020-01-01.`.

5.3
---
* Add the `normalizer` option to the `Unique` constraint
Expand Down
27 changes: 19 additions & 8 deletions src/Symfony/Component/Validator/ConstraintValidator.php
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,9 @@

namespace Symfony\Component\Validator;

use Symfony\Component\OptionsResolver\Exception\InvalidOptionsException;
use Symfony\Component\Validator\Context\ExecutionContextInterface;
use Symfony\Polyfill\Intl\Icu\Exception\NotImplementedException;

/**
* Base class for constraint validators.
Expand Down Expand Up @@ -84,19 +86,28 @@ protected function formatTypeOf($value)
*
* @return string The string representation of the passed value
*/
protected function formatValue($value, int $format = 0)
protected function formatValue($value, int $format = 0, ?string $dateFormat = null)
{
if (($format & self::PRETTY_DATE) && $value instanceof \DateTimeInterface) {
if (class_exists(\IntlDateFormatter::class)) {
$formatter = new \IntlDateFormatter(\Locale::getDefault(), \IntlDateFormatter::MEDIUM, \IntlDateFormatter::SHORT, 'UTC');

return $formatter->format(new \DateTime(
$value->format('Y-m-d H:i:s.u'),
new \DateTimeZone('UTC')
));
$formatter = new \IntlDateFormatter(\Locale::getDefault(), \IntlDateFormatter::MEDIUM, \IntlDateFormatter::SHORT, 'UTC', null, $dateFormat);

if (!$formatter) {
throw new InvalidOptionsException(intl_get_error_message(), intl_get_error_code());
}

try {
return $formatter->format(
new \DateTime(
$value->format('Y-m-d H:i:s.u'),
new \DateTimeZone('UTC')
)
);
} catch (NotImplementedException $e) {
}
}

return $value->format('Y-m-d H:i:s');
return $value->format($dateFormat ?? 'Y-m-d H:i:s');
}

if (\is_object($value)) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@
use Symfony\Component\PropertyAccess\PropertyAccess;
use Symfony\Component\Validator\Constraint;
use Symfony\Component\Validator\Exception\ConstraintDefinitionException;
use Symfony\Component\Validator\Exception\InvalidOptionsException;
use Symfony\Component\Validator\Exception\LogicException;

/**
Expand All @@ -27,6 +28,7 @@ abstract class AbstractComparison extends Constraint
public $message;
public $value;
public $propertyPath;
public $dateFormat;

/**
* {@inheritdoc}
Expand Down Expand Up @@ -57,6 +59,12 @@ public function __construct($value = null, $propertyPath = null, string $message
if (null !== $this->propertyPath && !class_exists(PropertyAccess::class)) {
throw new LogicException(sprintf('The "%s" constraint requires the Symfony PropertyAccess component to use the "propertyPath" option.', static::class));
}

$this->dateFormat = $options['dateFormat'] ?? null;

if (null !== $this->dateFormat && !\is_string($this->dateFormat)) {
throw new InvalidOptionsException('The "dateFormat" option must be null or a string.', $options);
}
}

/**
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -78,8 +78,8 @@ public function validate($value, Constraint $constraint)

if (!$this->compareValues($value, $comparedValue)) {
$violationBuilder = $this->context->buildViolation($constraint->message)
->setParameter('{{ value }}', $this->formatValue($value, self::OBJECT_TO_STRING | self::PRETTY_DATE))
->setParameter('{{ compared_value }}', $this->formatValue($comparedValue, self::OBJECT_TO_STRING | self::PRETTY_DATE))
->setParameter('{{ value }}', $this->formatValue($value, self::OBJECT_TO_STRING | self::PRETTY_DATE, $constraint->dateFormat))
->setParameter('{{ compared_value }}', $this->formatValue($comparedValue, self::OBJECT_TO_STRING | self::PRETTY_DATE, $constraint->dateFormat))
->setParameter('{{ compared_value_type }}', $this->formatTypeOf($comparedValue))
->setCode($this->getErrorCode());

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -179,7 +179,7 @@ abstract public function provideValidComparisonsToPropertyPath(): array;
* @param mixed $comparedValueString
* @param string $comparedValueType
*/
public function testInvalidComparisonToValue($dirtyValue, $dirtyValueAsString, $comparedValue, $comparedValueString, $comparedValueType)
public function testInvalidComparisonToValue($dirtyValue, $dirtyValueAsString, $comparedValue, $comparedValueString, $comparedValueType, $dateFormat = null)
{
// Conversion of dates to string differs between ICU versions
// Make sure we have the correct version loaded
Expand All @@ -189,6 +189,7 @@ public function testInvalidComparisonToValue($dirtyValue, $dirtyValueAsString, $

$constraint = $this->createConstraint(['value' => $comparedValue]);
$constraint->message = 'Constraint Message';
$constraint->dateFormat = $dateFormat;

$this->validator->validate($dirtyValue, $constraint);

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -74,6 +74,7 @@ public function provideInvalidComparisons(): array
[new \DateTime('2001-01-01'), 'Jan 1, 2001, 12:00 AM', '2000-01-01', 'Jan 1, 2000, 12:00 AM', 'DateTime'],
[new \DateTime('2001-01-01 UTC'), 'Jan 1, 2001, 12:00 AM', '2000-01-01 UTC', 'Jan 1, 2000, 12:00 AM', 'DateTime'],
[new ComparisonTest_Class(4), '4', new ComparisonTest_Class(5), '5', __NAMESPACE__.'\ComparisonTest_Class'],
[new \DateTime('2001-01-01'), '2001-01-01', new \DateTime('2000-01-01'), '2000-01-01', 'DateTime', 'Y-MM-dd'],
];
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -77,6 +77,7 @@ public function provideInvalidComparisons(): array
[new \DateTime('2000/01/01'), 'Jan 1, 2000, 12:00 AM', '2005/01/01', 'Jan 1, 2005, 12:00 AM', 'DateTime'],
[new \DateTime('2000/01/01 UTC'), 'Jan 1, 2000, 12:00 AM', '2005/01/01 UTC', 'Jan 1, 2005, 12:00 AM', 'DateTime'],
['b', '"b"', 'c', '"c"', 'string'],
[new \DateTime('2000/01/01'), '2000-01-01', new \DateTime('2005/01/01'), '2005-01-01', 'DateTime', 'Y-MM-dd'],
];
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -79,6 +79,7 @@ public function provideInvalidComparisons(): array
[new ComparisonTest_Class(5), '5', new ComparisonTest_Class(5), '5', __NAMESPACE__.'\ComparisonTest_Class'],
['22', '"22"', '333', '"333"', 'string'],
['22', '"22"', '22', '"22"', 'string'],
[new \DateTime('2000/01/01'), '2000-01-01', new \DateTime('2005/01/01'), '2005-01-01', 'DateTime', 'Y-MM-dd'],
];
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -92,6 +92,7 @@ public function provideInvalidComparisons(): array
[new \DateTime('2001-01-01'), 'Jan 1, 2001, 12:00 AM', new \DateTime('2001-01-01'), 'Jan 1, 2001, 12:00 AM', 'DateTime'],
[new \DateTime('2001-01-01'), 'Jan 1, 2001, 12:00 AM', new \DateTime('1999-01-01'), 'Jan 1, 1999, 12:00 AM', 'DateTime'],
[new ComparisonTest_Class(4), '4', new ComparisonTest_Class(5), '5', __NAMESPACE__.'\ComparisonTest_Class'],
[new \DateTime('2001-01-01'), '2001-01-01', new \DateTime('2001-01-01'), '2001-01-01', 'DateTime', 'Y-MM-dd'],
];
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -80,6 +80,7 @@ public function provideInvalidComparisons(): array
[new \DateTime('2010-01-01 UTC'), 'Jan 1, 2010, 12:00 AM', '2000-01-01 UTC', 'Jan 1, 2000, 12:00 AM', 'DateTime'],
[new ComparisonTest_Class(5), '5', new ComparisonTest_Class(4), '4', __NAMESPACE__.'\ComparisonTest_Class'],
['c', '"c"', 'b', '"b"', 'string'],
[new \DateTime('2010-01-01'), '2010-01-01', new \DateTime('2000-01-01'), '2000-01-01', 'DateTime', 'Y-MM-dd'],
];
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -78,6 +78,7 @@ public function provideInvalidComparisons(): array
[new ComparisonTest_Class(5), '5', new ComparisonTest_Class(5), '5', __NAMESPACE__.'\ComparisonTest_Class'],
[new ComparisonTest_Class(6), '6', new ComparisonTest_Class(5), '5', __NAMESPACE__.'\ComparisonTest_Class'],
['333', '"333"', '22', '"22"', 'string'],
[new \DateTime('2010-01-01'), '2010-01-01', new \DateTime('2000-01-01'), '2000-01-01', 'DateTime', 'Y-MM-dd'],
];
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -74,6 +74,7 @@ public function provideInvalidComparisons(): array
[new \DateTime('2000-01-01'), 'Jan 1, 2000, 12:00 AM', '2000-01-01', 'Jan 1, 2000, 12:00 AM', 'DateTime'],
[new \DateTime('2000-01-01 UTC'), 'Jan 1, 2000, 12:00 AM', '2000-01-01 UTC', 'Jan 1, 2000, 12:00 AM', 'DateTime'],
[new ComparisonTest_Class(5), '5', new ComparisonTest_Class(5), '5', __NAMESPACE__.'\ComparisonTest_Class'],
[new \DateTime('2000-01-01'), '2000-01-01', new \DateTime('2000-01-01'), '2000-01-01', 'DateTime', 'Y-MM-dd'],
];
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -90,6 +90,7 @@ public function provideInvalidComparisons(): array
['a', '"a"', 'a', '"a"', 'string'],
[$date, 'Jan 1, 2000, 12:00 AM', $date, 'Jan 1, 2000, 12:00 AM', 'DateTime'],
[$object, '2', $object, '2', __NAMESPACE__.'\ComparisonTest_Class'],
[$date, '2000-01-01', $date, '2000-01-01', 'DateTime', 'Y-MM-dd'],
];

return $comparisons;
Expand Down