DateTimeNormalizer.php in Drupal 8
File
core/modules/serialization/src/Normalizer/DateTimeNormalizer.php
View source
<?php
namespace Drupal\serialization\Normalizer;
use Drupal\Core\Config\ConfigFactoryInterface;
use Drupal\Core\TypedData\Type\DateTimeInterface;
use Symfony\Component\Serializer\Exception\UnexpectedValueException;
use Symfony\Component\Serializer\Normalizer\DenormalizerInterface;
class DateTimeNormalizer extends NormalizerBase implements DenormalizerInterface {
protected $allowedFormats = [
'RFC 3339' => \DateTime::RFC3339,
'ISO 8601' => \DateTime::ISO8601,
];
protected $supportedInterfaceOrClass = DateTimeInterface::class;
protected $systemDateConfig;
public function __construct(ConfigFactoryInterface $config_factory) {
$this->systemDateConfig = $config_factory
->get('system.date');
}
public function normalize($datetime, $format = NULL, array $context = []) {
assert($datetime instanceof DateTimeInterface);
$drupal_date_time = $datetime
->getDateTime();
if ($drupal_date_time === NULL) {
return $drupal_date_time;
}
return $drupal_date_time
->setTimezone($this
->getNormalizationTimezone())
->format(\DateTime::RFC3339);
}
protected function getNormalizationTimezone() {
$default_site_timezone = $this->systemDateConfig
->get('timezone.default');
return new \DateTimeZone($default_site_timezone);
}
public function denormalize($data, $class, $format = NULL, array $context = []) {
if (!is_string($data) && !is_numeric($data)) {
return $data;
}
$allowed_formats = isset($context['datetime_allowed_formats']) ? $context['datetime_allowed_formats'] : $this->allowedFormats;
foreach ($allowed_formats as $format) {
$date = \DateTime::createFromFormat($format, $data);
$errors = \DateTime::getLastErrors();
if ($date !== FALSE && empty($errors['errors']) && empty($errors['warnings'])) {
return $date;
}
}
$format_strings = [];
foreach ($allowed_formats as $label => $format) {
$format_strings[] = "\"{$format}\" ({$label})";
}
$formats = implode(', ', $format_strings);
throw new UnexpectedValueException(sprintf('The specified date "%s" is not in an accepted format: %s.', $data, $formats));
}
}