You are here

public function ContentEntityNormalizer::denormalize in Default Content for D8 2.0.x

Converts the normalized data back into a content entity.

Parameters

array $data: The normalized data.

Return value

\Drupal\Core\Entity\ContentEntityInterface The denormalized content entity.

Overrides ContentEntityNormalizerInterface::denormalize

1 call to ContentEntityNormalizer::denormalize()
ContentEntityNormalizer::setFieldValues in src/Normalizer/ContentEntityNormalizer.php
Set field values based on the normalized data.

File

src/Normalizer/ContentEntityNormalizer.php, line 153

Class

ContentEntityNormalizer
Normalizes and denormalizes content entities.

Namespace

Drupal\default_content\Normalizer

Code

public function denormalize(array $data) {
  if (!isset($data['_meta']['entity_type'])) {
    throw new UnexpectedValueException('The entity type metadata must be specified.');
  }
  if (!isset($data['_meta']['uuid'])) {
    throw new UnexpectedValueException('The uuid metadata must be specified.');
  }
  $is_root = FALSE;
  if ($this->dependencies === NULL && !empty($data['_meta']['depends'])) {
    $is_root = TRUE;
    $this->dependencies = $data['_meta']['depends'];
  }
  $entity_type = $this->entityTypeManager
    ->getDefinition($data['_meta']['entity_type']);
  $values = [
    'uuid' => $data['_meta']['uuid'],
  ];
  if (!empty($data['_meta']['bundle'])) {
    $values[$entity_type
      ->getKey('bundle')] = $data['_meta']['bundle'];
  }
  if (!empty($data['_meta']['default_langcode'])) {
    $data = $this
      ->verifyNormalizedLanguage($data);
    $values[$entity_type
      ->getKey('langcode')] = $data['_meta']['default_langcode'];
  }

  /** @var \Drupal\Core\Entity\ContentEntityInterface $entity */
  $entity = $this->entityTypeManager
    ->getStorage($entity_type
    ->id())
    ->create($values);
  foreach ($data['default'] as $field_name => $values) {
    $this
      ->setFieldValues($entity, $field_name, $values);
  }
  if (!empty($data['translations'])) {
    foreach ($data['translations'] as $langcode => $translation_data) {
      if ($this->languageManager
        ->getLanguage($langcode)) {
        $translation = $entity
          ->addTranslation($langcode, $entity
          ->toArray());
        foreach ($translation_data as $field_name => $values) {
          $this
            ->setFieldValues($translation, $field_name, $values);
        }
      }
    }
  }
  if ($is_root) {
    $this->dependencies = NULL;
  }
  return $entity;
}