4 * This file is part of the Symfony package.
6 * (c) Fabien Potencier <fabien@symfony.com>
8 * For the full copyright and license information, please view the LICENSE
9 * file that was distributed with this source code.
12 namespace Symfony\Component\Serializer\Normalizer;
14 use Symfony\Component\Serializer\Exception\InvalidArgumentException;
15 use Symfony\Component\Serializer\Exception\UnexpectedValueException;
18 * Normalizes an instance of {@see \DateInterval} to an interval string.
19 * Denormalizes an interval string to an instance of {@see \DateInterval}.
21 * @author Jérôme Parmentier <jerome@prmntr.me>
23 class DateIntervalNormalizer implements NormalizerInterface, DenormalizerInterface
25 const FORMAT_KEY = 'dateinterval_format';
30 * @param string $format
32 public function __construct($format = 'P%yY%mM%dDT%hH%iM%sS')
34 $this->format = $format;
40 * @throws InvalidArgumentException
42 public function normalize($object, $format = null, array $context = array())
44 if (!$object instanceof \DateInterval) {
45 throw new InvalidArgumentException('The object must be an instance of "\DateInterval".');
48 $dateIntervalFormat = isset($context[self::FORMAT_KEY]) ? $context[self::FORMAT_KEY] : $this->format;
50 return $object->format($dateIntervalFormat);
56 public function supportsNormalization($data, $format = null)
58 return $data instanceof \DateInterval;
64 * @throws InvalidArgumentException
65 * @throws UnexpectedValueException
67 public function denormalize($data, $class, $format = null, array $context = array())
69 if (!\is_string($data)) {
70 throw new InvalidArgumentException(sprintf('Data expected to be a string, %s given.', \gettype($data)));
73 if (!$this->isISO8601($data)) {
74 throw new UnexpectedValueException('Expected a valid ISO 8601 interval string.');
77 $dateIntervalFormat = isset($context[self::FORMAT_KEY]) ? $context[self::FORMAT_KEY] : $this->format;
79 $valuePattern = '/^'.preg_replace('/%([yYmMdDhHiIsSwW])(\w)/', '(?P<$1>\d+)$2', $dateIntervalFormat).'$/';
80 if (!preg_match($valuePattern, $data)) {
81 throw new UnexpectedValueException(sprintf('Value "%s" contains intervals not accepted by format "%s".', $data, $dateIntervalFormat));
85 return new \DateInterval($data);
86 } catch (\Exception $e) {
87 throw new UnexpectedValueException($e->getMessage(), $e->getCode(), $e);
94 public function supportsDenormalization($data, $type, $format = null)
96 return \DateInterval::class === $type;
99 private function isISO8601($string)
101 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);