You are here

public function ParagraphNormalizer::denormalize in Replication 8

Overrides ContentEntityNormalizer::denormalize

File

src/Normalizer/ParagraphNormalizer.php, line 40

Class

ParagraphNormalizer

Namespace

Drupal\replication\Normalizer

Code

public function denormalize($data, $class, $format = NULL, array $context = []) {
  if (!empty($data['@context']['@language'])) {
    $language = $data['@context']['@language'];
  }
  if (!empty($data[$language]['parent_id'][0]['value']['entity_type_id']) && !empty($data[$language]['parent_id'][0]['value']['target_uuid'])) {
    $entity_type_id = $data[$language]['parent_id'][0]['value']['entity_type_id'];
    $target_uuid = $data[$language]['parent_id'][0]['value']['target_uuid'];
    $storage = $this->entityManager
      ->getStorage($entity_type_id);
    if (!empty($context['workspace'])) {
      $storage
        ->useWorkspace($context['workspace']
        ->id());
    }
    $parents = $storage
      ->loadByProperties([
      'uuid' => $target_uuid,
    ]);
    $parent = reset($parents);
    if ($parent instanceof ContentEntityInterface && $parent
      ->id()) {
      $data[$language]['parent_id'][0]['value'] = $parent
        ->id();
    }
    elseif (!$parent) {

      // Create a new entity as stub.
      $selection_instance = $this->selectionManager
        ->getInstance([
        'target_type' => $entity_type_id,
      ]);
      $bundle_key = $storage
        ->getEntityType()
        ->getKey('bundle');
      $bundle = $entity_type_id;
      if (!empty($data[$language]['parent_id'][0]['value'][$bundle_key])) {
        $bundle = $data[$language]['parent_id'][0]['value'][$bundle_key];
      }
      $parent = $selection_instance
        ->createNewEntity($entity_type_id, $bundle, rand(), 1);

      // Indicate that this revision is a stub.
      $parent->_rev->is_stub = TRUE;
      $parent->langcode->value = $language;
      $parent->uuid->value = $target_uuid;
      if (!empty($context['workspace'])) {
        $parent->workspace->entity = $context['workspace'];
      }
      $parent
        ->save();
      $data[$language]['parent_id'][0]['value'] = $parent
        ->id();
    }
    $storage
      ->useWorkspace(NULL);
  }
  return parent::denormalize($data, $class, $format, $context);
}