Skip to content

Commit

Permalink
[Validator][ConstraintValidator] Safe fail on invalid timezones
Browse files Browse the repository at this point in the history
Co-authored-by: Scott Dawson <scott@loyaltycorp.com.au>
  • Loading branch information
fancyweb and Scott Dawson committed Dec 9, 2019
1 parent bf877b8 commit 97b9745
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 7 deletions.
10 changes: 8 additions & 2 deletions src/Symfony/Component/Validator/ConstraintValidator.php
Expand Up @@ -87,8 +87,14 @@ protected function formatValue($value, $format = 0)
{
if (($format & self::PRETTY_DATE) && $value instanceof \DateTimeInterface) {
if (class_exists('IntlDateFormatter')) {
$locale = \Locale::getDefault();
$formatter = new \IntlDateFormatter($locale, \IntlDateFormatter::MEDIUM, \IntlDateFormatter::SHORT, $value->getTimezone());
$formatter = new \IntlDateFormatter(\Locale::getDefault(), \IntlDateFormatter::MEDIUM, \IntlDateFormatter::SHORT);

$timezone = $value->getTimezone();
if ('Z' === $timezone->getName()) {
$timezone = new \DateTimeZone('UTC');
}

$formatter->setTimeZone($timezone);

// neither the native nor the stub IntlDateFormatter support
// DateTimeImmutable as of yet
Expand Down
15 changes: 10 additions & 5 deletions src/Symfony/Component/Validator/Tests/ConstraintValidatorTest.php
Expand Up @@ -22,12 +22,17 @@ final class ConstraintValidatorTest extends TestCase
*/
public function testFormatValue($expected, $value, $format = 0)
{
$default = date_default_timezone_get();
date_default_timezone_set('Europe/Moscow');

$this->assertSame($expected, (new TestFormatValueConstraintValidator())->formatValueProxy($value, $format));

date_default_timezone_set($default);
}

public function formatValueProvider()
{
$data = [
return [
['true', true],
['false', false],
['null', null],
Expand All @@ -36,11 +41,11 @@ public function formatValueProvider()
['array', []],
['object', $toString = new TestToStringObject()],
['ccc', $toString, ConstraintValidator::OBJECT_TO_STRING],
['object', $dateTime = (new \DateTimeImmutable('@0'))->setTimezone(new \DateTimeZone('UTC'))],
[class_exists(\IntlDateFormatter::class) ? 'Jan 1, 1970, 12:00 AM' : '1970-01-01 00:00:00', $dateTime, ConstraintValidator::PRETTY_DATE],
['object', $dateTime = (new \DateTimeImmutable('1971-02-02T08:00:00'))->setTimezone(new \DateTimeZone('UTC'))],
[class_exists(\IntlDateFormatter::class) ? 'Oct 4, 2019, 11:02 AM' : '2019-10-04 11:02:03', new \DateTimeImmutable('2019-10-04T11:02:03+09:00'), ConstraintValidator::PRETTY_DATE],
[class_exists(\IntlDateFormatter::class) ? 'Feb 2, 1971, 8:00 AM' : '1971-02-02 08:00:00', $dateTime, ConstraintValidator::PRETTY_DATE],
[class_exists(\IntlDateFormatter::class) ? 'Jan 1, 1970, 6:00 AM' : '1970-01-01 6:00:00', (new \DateTimeImmutable('1970-01-01T06:00:00'))->setTimezone(new \DateTimeZone('Z')), ConstraintValidator::PRETTY_DATE],
];

return $data;
}
}

Expand Down

0 comments on commit 97b9745

Please sign in to comment.