Skip to content

Commit 9fa3632

Browse files
committed
zero parts can be omitted in date interval input
1 parent 7c470ac commit 9fa3632

File tree

2 files changed

+9
-1
lines changed

2 files changed

+9
-1
lines changed

Normalizer/DateIntervalNormalizer.php

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -105,7 +105,7 @@ public function denormalize($data, $type, $format = null, array $context = [])
105105
$dateIntervalFormat = substr($dateIntervalFormat, 2);
106106
break;
107107
}
108-
$valuePattern = '/^'.$signPattern.preg_replace('/%([yYmMdDhHiIsSwW])(\w)/', '(?P<$1>\d+)$2', $dateIntervalFormat).'$/';
108+
$valuePattern = '/^'.$signPattern.preg_replace('/%([yYmMdDhHiIsSwW])(\w)/', '(?:(?P<$1>\d+)$2)?', preg_replace('/(T.*)$/', '($1)?', $dateIntervalFormat)).'$/';
109109
if (!preg_match($valuePattern, $data)) {
110110
throw new UnexpectedValueException(sprintf('Value "%s" contains intervals not accepted by format "%s".', $data, $dateIntervalFormat));
111111
}

Tests/Normalizer/DateIntervalNormalizerTest.php

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -124,6 +124,14 @@ public function testLegacyDenormalizeUsingFormatPassedInConstructor($format, $in
124124
$this->doTestDenormalizeUsingFormatPassedInConstructor($format, $input, $output, true);
125125
}
126126

127+
public function testDenormalizeIntervalsWithOmittedPartsBeingZero()
128+
{
129+
$normalizer = new DateIntervalNormalizer();
130+
131+
$this->assertDateIntervalEquals($this->getInterval('P3Y2M4DT0H0M0S'), $normalizer->denormalize('P3Y2M4D', \DateInterval::class));
132+
$this->assertDateIntervalEquals($this->getInterval('P0Y0M0DT12H34M0S'), $normalizer->denormalize('PT12H34M', \DateInterval::class));
133+
}
134+
127135
private function doTestDenormalizeUsingFormatPassedInConstructor($format, $input, $output, bool $legacy = false)
128136
{
129137
$normalizer = $legacy ? new DateIntervalNormalizer($format) : new DateIntervalNormalizer([DateIntervalNormalizer::FORMAT_KEY => $format]);

0 commit comments

Comments
 (0)