-
-
Notifications
You must be signed in to change notification settings - Fork 9.6k
[Serializer][FrameworkBundle] Add a DateInterval normalizer #23747
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
Closed
Changes from all commits
Commits
Show all changes
8 commits
Select commit
Hold shift + click to select a range
b28839b
Add a DateInterval normalizer
e86f5a1
Fix wrong format in tests
643ea73
Fix wrong comments
71e8fa7
Update non ISO 8601 interval string exception message + tests
2d23e5c
Switch to sprintf()
Lctrs ec7f37f
Update CHANGELOG.md
36acaf0
CS
db7e9cc
Partially revert previous commit
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
106 changes: 106 additions & 0 deletions
106
src/Symfony/Component/Serializer/Normalizer/DateIntervalNormalizer.php
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,106 @@ | ||
<?php | ||
|
||
/* | ||
* This file is part of the Symfony package. | ||
* | ||
* (c) Fabien Potencier <fabien@symfony.com> | ||
* | ||
* For the full copyright and license information, please view the LICENSE | ||
* file that was distributed with this source code. | ||
*/ | ||
|
||
namespace Symfony\Component\Serializer\Normalizer; | ||
|
||
use Symfony\Component\Serializer\Exception\InvalidArgumentException; | ||
use Symfony\Component\Serializer\Exception\UnexpectedValueException; | ||
|
||
/** | ||
* Normalizes an instance of {@see \DateInterval} to an interval string. | ||
* Denormalizes an interval string to an instance of {@see \DateInterval}. | ||
* | ||
* @author Jérôme Parmentier <jerome@prmntr.me> | ||
*/ | ||
class DateIntervalNormalizer implements NormalizerInterface, DenormalizerInterface | ||
{ | ||
const FORMAT_KEY = 'dateinterval_format'; | ||
|
||
/** | ||
* @var string | ||
*/ | ||
private $format; | ||
|
||
/** | ||
* @param string $format | ||
*/ | ||
public function __construct($format = 'P%yY%mM%dDT%hH%iM%sS') | ||
{ | ||
$this->format = $format; | ||
} | ||
|
||
/** | ||
* {@inheritdoc} | ||
* | ||
* @throws InvalidArgumentException | ||
*/ | ||
public function normalize($object, $format = null, array $context = array()) | ||
{ | ||
if (!$object instanceof \DateInterval) { | ||
throw new InvalidArgumentException('The object must be an instance of "\DateInterval".'); | ||
} | ||
|
||
$dateIntervalFormat = isset($context[self::FORMAT_KEY]) ? $context[self::FORMAT_KEY] : $this->format; | ||
|
||
return $object->format($dateIntervalFormat); | ||
} | ||
|
||
/** | ||
* {@inheritdoc} | ||
*/ | ||
public function supportsNormalization($data, $format = null) | ||
{ | ||
return $data instanceof \DateInterval; | ||
} | ||
|
||
/** | ||
* {@inheritdoc} | ||
* | ||
* @throws InvalidArgumentException | ||
* @throws UnexpectedValueException | ||
*/ | ||
public function denormalize($data, $class, $format = null, array $context = array()) | ||
{ | ||
if (!is_string($data)) { | ||
throw new InvalidArgumentException(sprintf('Data expected to be a string, %s given.', gettype($data))); | ||
} | ||
|
||
if (!$this->isISO8601($data)) { | ||
throw new UnexpectedValueException('Expected a valid ISO 8601 interval string.'); | ||
} | ||
|
||
$dateIntervalFormat = isset($context[self::FORMAT_KEY]) ? $context[self::FORMAT_KEY] : $this->format; | ||
|
||
$valuePattern = '/^'.preg_replace('/%([yYmMdDhHiIsSwW])(\w)/', '(?P<$1>\d+)$2', $dateIntervalFormat).'$/'; | ||
if (!preg_match($valuePattern, $data)) { | ||
throw new UnexpectedValueException(sprintf('Value "%s" contains intervals not accepted by format "%s".', $data, $dateIntervalFormat)); | ||
} | ||
|
||
try { | ||
return new \DateInterval($data); | ||
} catch (\Exception $e) { | ||
throw new UnexpectedValueException($e->getMessage(), $e->getCode(), $e); | ||
} | ||
} | ||
|
||
/** | ||
* {@inheritdoc} | ||
*/ | ||
public function supportsDenormalization($data, $type, $format = null) | ||
{ | ||
return \DateInterval::class === $type; | ||
} | ||
|
||
private function isISO8601($string) | ||
{ | ||
return preg_match('/^P(?=\w*(?:\d|%\w))(?:\d+Y|%[yY]Y)?(?:\d+M|%[mM]M)?(?:(?:\d+D|%[dD]D)|(?:\d+W|%[wW]W))?(?:T(?:\d+H|[hH]H)?(?:\d+M|[iI]M)?(?:\d+S|[sS]S)?)?$/', $string); | ||
} | ||
} |
137 changes: 137 additions & 0 deletions
137
src/Symfony/Component/Serializer/Tests/Normalizer/DateIntervalNormalizerTest.php
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,137 @@ | ||
<?php | ||
|
||
namespace Symfony\Component\Serializer\Tests\Normalizer; | ||
|
||
use PHPUnit\Framework\TestCase; | ||
use Symfony\Component\Serializer\Normalizer\DateIntervalNormalizer; | ||
|
||
/** | ||
* @author Jérôme Parmentier <jerome@prmntr.me> | ||
*/ | ||
class DateIntervalNormalizerTest extends TestCase | ||
{ | ||
/** | ||
* @var DateIntervalNormalizer | ||
*/ | ||
private $normalizer; | ||
|
||
protected function setUp() | ||
{ | ||
$this->normalizer = new DateIntervalNormalizer(); | ||
} | ||
|
||
public function dataProviderISO() | ||
{ | ||
$data = array( | ||
array('P%YY%MM%DDT%HH%IM%SS', 'P00Y00M00DT00H00M00S', 'PT0S'), | ||
array('P%yY%mM%dDT%hH%iM%sS', 'P0Y0M0DT0H0M0S', 'PT0S'), | ||
array('P%yY%mM%dDT%hH%iM%sS', 'P10Y2M3DT16H5M6S', 'P10Y2M3DT16H5M6S'), | ||
array('P%yY%mM%dDT%hH%iM', 'P10Y2M3DT16H5M', 'P10Y2M3DT16H5M'), | ||
array('P%yY%mM%dDT%hH', 'P10Y2M3DT16H', 'P10Y2M3DT16H'), | ||
array('P%yY%mM%dD', 'P10Y2M3D', 'P10Y2M3DT0H'), | ||
); | ||
|
||
return $data; | ||
} | ||
|
||
public function testSupportsNormalization() | ||
{ | ||
$this->assertTrue($this->normalizer->supportsNormalization(new \DateInterval('P00Y00M00DT00H00M00S'))); | ||
$this->assertFalse($this->normalizer->supportsNormalization(new \stdClass())); | ||
} | ||
|
||
public function testNormalize() | ||
{ | ||
$this->assertEquals('P0Y0M0DT0H0M0S', $this->normalizer->normalize(new \DateInterval('PT0S'))); | ||
} | ||
|
||
/** | ||
* @dataProvider dataProviderISO | ||
*/ | ||
public function testNormalizeUsingFormatPassedInContext($format, $output, $input) | ||
{ | ||
$this->assertEquals($output, $this->normalizer->normalize(new \DateInterval($input), null, array(DateIntervalNormalizer::FORMAT_KEY => $format))); | ||
} | ||
|
||
/** | ||
* @dataProvider dataProviderISO | ||
*/ | ||
public function testNormalizeUsingFormatPassedInConstructor($format, $output, $input) | ||
{ | ||
$this->assertEquals($output, (new DateIntervalNormalizer($format))->normalize(new \DateInterval($input))); | ||
} | ||
|
||
/** | ||
* @expectedException \Symfony\Component\Serializer\Exception\InvalidArgumentException | ||
* @expectedExceptionMessage The object must be an instance of "\DateInterval". | ||
*/ | ||
public function testNormalizeInvalidObjectThrowsException() | ||
{ | ||
$this->normalizer->normalize(new \stdClass()); | ||
} | ||
|
||
public function testSupportsDenormalization() | ||
{ | ||
$this->assertTrue($this->normalizer->supportsDenormalization('P00Y00M00DT00H00M00S', \DateInterval::class)); | ||
$this->assertFalse($this->normalizer->supportsDenormalization('foo', 'Bar')); | ||
} | ||
|
||
public function testDenormalize() | ||
{ | ||
$this->assertDateIntervalEquals(new \DateInterval('P00Y00M00DT00H00M00S'), $this->normalizer->denormalize('P00Y00M00DT00H00M00S', \DateInterval::class)); | ||
} | ||
|
||
/** | ||
* @dataProvider dataProviderISO | ||
*/ | ||
public function testDenormalizeUsingFormatPassedInContext($format, $input, $output) | ||
{ | ||
$this->assertDateIntervalEquals(new \DateInterval($output), $this->normalizer->denormalize($input, \DateInterval::class, null, array(DateIntervalNormalizer::FORMAT_KEY => $format))); | ||
} | ||
|
||
/** | ||
* @dataProvider dataProviderISO | ||
*/ | ||
public function testDenormalizeUsingFormatPassedInConstructor($format, $input, $output) | ||
{ | ||
$this->assertDateIntervalEquals(new \DateInterval($output), (new DateIntervalNormalizer($format))->denormalize($input, \DateInterval::class)); | ||
} | ||
|
||
/** | ||
* @expectedException \Symfony\Component\Serializer\Exception\InvalidArgumentException | ||
*/ | ||
public function testDenormalizeExpectsString() | ||
{ | ||
$this->normalizer->denormalize(1234, \DateInterval::class); | ||
} | ||
|
||
/** | ||
* @expectedException \Symfony\Component\Serializer\Exception\UnexpectedValueException | ||
* @expectedExceptionMessage Expected a valid ISO 8601 interval string. | ||
*/ | ||
public function testDenormalizeNonISO8601IntervalStringThrowsException() | ||
{ | ||
$this->normalizer->denormalize('10 years 2 months 3 days', \DateInterval::class, null); | ||
} | ||
|
||
/** | ||
* @expectedException \Symfony\Component\Serializer\Exception\UnexpectedValueException | ||
*/ | ||
public function testDenormalizeInvalidDataThrowsException() | ||
{ | ||
$this->normalizer->denormalize('invalid interval', \DateInterval::class); | ||
} | ||
|
||
/** | ||
* @expectedException \Symfony\Component\Serializer\Exception\UnexpectedValueException | ||
*/ | ||
public function testDenormalizeFormatMismatchThrowsException() | ||
{ | ||
$this->normalizer->denormalize('P00Y00M00DT00H00M00S', \DateInterval::class, null, array(DateIntervalNormalizer::FORMAT_KEY => 'P%yY%mM%dD')); | ||
} | ||
|
||
private function assertDateIntervalEquals(\DateInterval $expected, \DateInterval $actual) | ||
{ | ||
$this->assertEquals($expected->format('%RP%yY%mM%dDT%hH%iM%sS'), $actual->format('%RP%yY%mM%dDT%hH%iM%sS')); | ||
} | ||
} |
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
@ogizanagi are you okay with this priority ? Or should I change it to -930 to be more consistent with other normalizers ?
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Looks good to me :)