DateTimeIso8601Normalizer.php in Drupal 9
File
core/modules/serialization/src/Normalizer/DateTimeIso8601Normalizer.php
View source
<?php
namespace Drupal\serialization\Normalizer;
use Drupal\Core\TypedData\Plugin\DataType\DateTimeIso8601;
use Drupal\datetime\Plugin\Field\FieldType\DateTimeItem;
use Drupal\datetime\Plugin\Field\FieldType\DateTimeItemInterface;
use Symfony\Component\Serializer\Exception\InvalidArgumentException;
class DateTimeIso8601Normalizer extends DateTimeNormalizer {
protected $allowedFormats = [
'RFC 3339' => \DateTime::RFC3339,
'ISO 8601' => \DateTime::ISO8601,
'date-only' => 'Y-m-d',
];
protected $supportedInterfaceOrClass = DateTimeIso8601::class;
public function normalize($datetime, $format = NULL, array $context = []) {
assert($datetime instanceof DateTimeIso8601);
$field_item = $datetime
->getParent();
if ($field_item instanceof DateTimeItem && $field_item
->getFieldDefinition()
->getFieldStorageDefinition()
->getSetting('datetime_type') === DateTimeItem::DATETIME_TYPE_DATE) {
$drupal_date_time = $datetime
->getDateTime();
if ($drupal_date_time === NULL) {
return $drupal_date_time;
}
return $drupal_date_time
->format($this->allowedFormats['date-only']);
}
return parent::normalize($datetime, $format, $context);
}
public function denormalize($data, $class, $format = NULL, array $context = []) {
$field_definition = isset($context['target_instance']) ? $context['target_instance']
->getFieldDefinition() : (isset($context['field_definition']) ? $context['field_definition'] : NULL);
if ($field_definition === NULL) {
throw new InvalidArgumentException('$context[\'target_instance\'] or $context[\'field_definition\'] must be set to denormalize with the DateTimeIso8601Normalizer');
}
$datetime_type = $field_definition
->getSetting('datetime_type');
$is_date_only = $datetime_type === DateTimeItem::DATETIME_TYPE_DATE;
if ($is_date_only) {
$context['datetime_allowed_formats'] = array_intersect_key($this->allowedFormats, [
'date-only' => TRUE,
]);
$datetime = parent::denormalize($data, $class, $format, $context);
if (!$datetime instanceof \DateTime) {
return $datetime;
}
return $datetime
->format(DateTimeItemInterface::DATE_STORAGE_FORMAT);
}
$context['datetime_allowed_formats'] = array_diff_key($this->allowedFormats, [
'date-only' => TRUE,
]);
$datetime = parent::denormalize($data, $class, $format, $context);
if (!$datetime instanceof \DateTime) {
return $datetime;
}
$datetime
->setTimezone(new \DateTimeZone(DateTimeItemInterface::STORAGE_TIMEZONE));
return $datetime
->format(DateTimeItemInterface::DATETIME_STORAGE_FORMAT);
}
}