zero parts can be omitted in date interval input

This commit is contained in:
Christian Flothmann 2021-02-26 13:01:23 +01:00
parent a5683c5324
commit c316708669
2 changed files with 9 additions and 1 deletions

View File

@ -105,7 +105,7 @@ class DateIntervalNormalizer implements NormalizerInterface, DenormalizerInterfa
$dateIntervalFormat = substr($dateIntervalFormat, 2);
break;
}
$valuePattern = '/^'.$signPattern.preg_replace('/%([yYmMdDhHiIsSwW])(\w)/', '(?P<$1>\d+)$2', $dateIntervalFormat).'$/';
$valuePattern = '/^'.$signPattern.preg_replace('/%([yYmMdDhHiIsSwW])(\w)/', '(?:(?P<$1>\d+)$2)?', preg_replace('/(T.*)$/', '($1)?', $dateIntervalFormat)).'$/';
if (!preg_match($valuePattern, $data)) {
throw new UnexpectedValueException(sprintf('Value "%s" contains intervals not accepted by format "%s".', $data, $dateIntervalFormat));
}

View File

@ -124,6 +124,14 @@ class DateIntervalNormalizerTest extends TestCase
$this->doTestDenormalizeUsingFormatPassedInConstructor($format, $input, $output, true);
}
public function testDenormalizeIntervalsWithOmittedPartsBeingZero()
{
$normalizer = new DateIntervalNormalizer();
$this->assertDateIntervalEquals($this->getInterval('P3Y2M4DT0H0M0S'), $normalizer->denormalize('P3Y2M4D', \DateInterval::class));
$this->assertDateIntervalEquals($this->getInterval('P0Y0M0DT12H34M0S'), $normalizer->denormalize('PT12H34M', \DateInterval::class));
}
private function doTestDenormalizeUsingFormatPassedInConstructor($format, $input, $output, bool $legacy = false)
{
$normalizer = $legacy ? new DateIntervalNormalizer($format) : new DateIntervalNormalizer([DateIntervalNormalizer::FORMAT_KEY => $format]);