You are here

protected function TimeStampItemNormalizerTrait::constructValue in Drupal 8

File

core/modules/serialization/src/Normalizer/TimeStampItemNormalizerTrait.php, line 61

Class

TimeStampItemNormalizerTrait
A trait for TimestampItem normalization functionality.

Namespace

Drupal\serialization\Normalizer

Code

protected function constructValue($data, $context) {

  // Loop through the allowed formats and create a TimestampItem from the
  // input data if it matches the defined pattern. Since the formats are
  // unambiguous (i.e., they reference an absolute time with a defined time
  // zone), only one will ever match.
  $timezone = new \DateTimeZone('UTC');

  // First check for a provided format.
  if (!empty($data['format']) && in_array($data['format'], $this->allowedFormats)) {
    $date = \DateTime::createFromFormat($data['format'], $data['value'], $timezone);
    return [
      'value' => $date
        ->getTimestamp(),
    ];
  }
  else {
    foreach ($this->allowedFormats as $format) {
      if (($date = \DateTime::createFromFormat($format, $data['value'], $timezone)) !== FALSE) {
        return [
          'value' => $date
            ->getTimestamp(),
        ];
      }
    }
  }
  $format_strings = [];
  foreach ($this->allowedFormats 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['value'], $formats));
}