requestStack = $requestStack; $this->parameterBag = $parameterBag; } public function denormalize($data, $type, $format = null, array $context = []) { if (null === $data) { return null; } switch ($type) { case DateTime::class: $result = DateTime::createFromFormat(DateTimeInterface::ISO8601, $data['datetime']); break; case DateTimeInterface::class: case DateTimeImmutable::class: $result = DateTimeImmutable::createFromFormat(DateTimeInterface::ISO8601, $data['datetime']); break; default: throw new UnexpectedValueException(); } if (false === $result) { return null; } return $result; } public function normalize($date, $format = null, array $context = []) { /** @var DateTimeInterface $date */ switch ($format) { case 'json': return [ 'datetime' => $date->format(DateTimeInterface::ISO8601), ]; case 'docgen': if (null === $date) { return [ 'long' => '', 'short' => '', ]; } $hasTime = $date->format('His') !== '000000'; $request = $this->requestStack->getCurrentRequest(); $locale = null !== $request ? $request->getLocale() : $this->parameterBag->get('kernel.default_locale'); $formatterLong = IntlDateFormatter::create( $locale, IntlDateFormatter::LONG, $hasTime ? IntlDateFormatter::SHORT : IntlDateFormatter::NONE ); $formatterShort = IntlDateFormatter::create( $locale, IntlDateFormatter::SHORT, $hasTime ? IntlDateFormatter::SHORT : IntlDateFormatter::NONE ); return [ 'short' => $formatterShort->format($date), 'long' => $formatterLong->format($date), ]; } } public function supportsDenormalization($data, $type, $format = null): bool { return DateTimeInterface::class === $type || DateTime::class === $type || DateTimeImmutable::class === $type || (is_array($data) && array_key_exists('datetime', $data)); } public function supportsNormalization($data, $format = null, array $context = []): bool { if ('json' === $format) { return $data instanceof DateTimeInterface; } if ('docgen' === $format) { return $data instanceof DateTimeInterface || ( null === $data && array_key_exists('docgen:expects', $context) && ( DateTimeInterface::class === $context['docgen:expects'] || DateTime::class === $context['docgen:expects'] || DateTimeImmutable::class === $context['docgen:expects'] ) ); } return false; } }