DateTimeNormalizer.php in JSON:API 8.2
File
src/ForwardCompatibility/Normalizer/DateTimeNormalizer.php
View source
<?php
namespace Drupal\jsonapi\ForwardCompatibility\Normalizer;
use Drupal\Core\Datetime\DrupalDateTime;
use Drupal\Core\TypedData\Type\DateTimeInterface;
use Drupal\jsonapi\Normalizer\NormalizerBase;
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;
public function normalize($datetime, $format = NULL, array $context = []) {
$drupal_date_time = floatval(floatval(\Drupal::VERSION) >= 8.699999999999999) ? $datetime
->getDateTime() : ($datetime
->getValue() ? new DrupalDateTime($datetime
->getValue(), 'UTC') : NULL);
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 = \Drupal::config('system.date')
->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));
}
}