You are here

public function Parents::decorateNormalization in Content Synchronization 3.0.x

Same name and namespace in other branches
  1. 8.2 src/Plugin/SyncNormalizerDecorator/Parents.php \Drupal\content_sync\Plugin\SyncNormalizerDecorator\Parents::decorateNormalization()

Parameters

array $normalized_entity:

\Drupal\Core\Entity\ContentEntityInterface $entity:

$format:

array $context:

Overrides SyncNormalizerDecoratorBase::decorateNormalization

File

src/Plugin/SyncNormalizerDecorator/Parents.php, line 52

Class

Parents
Plugin annotation @SyncNormalizerDecorator( id = "parents", name = @Translation("Parents"), )

Namespace

Drupal\content_sync\Plugin\SyncNormalizerDecorator

Code

public function decorateNormalization(array &$normalized_entity, ContentEntityInterface $entity, $format, array $context = []) {
  if ($entity
    ->hasField('parent')) {
    $entity_type = $entity
      ->getEntityTypeId();
    $storage = $this->entityTypeManager
      ->getStorage($entity_type);
    $existing_parent_uuids = [];
    if (!empty($normalized_entity['parent'])) {
      foreach ($normalized_entity['parent'] as $delta => $field_item_data) {
        if (empty($field_item_data['target_uuid'])) {
          continue;
        }
        $existing_parent_uuids[] = $field_item_data['target_uuid'];
      }
    }
    if (method_exists($storage, 'loadParents')) {
      $parents = $storage
        ->loadParents($entity
        ->id());
      foreach ($parents as $parent_key => $parent) {
        if (in_array($parent
          ->uuid(), $existing_parent_uuids)) {
          continue;
        }
        $normalized_entity['parent'][] = [
          'target_type' => $entity_type,
          'target_uuid' => $parent
            ->uuid(),
        ];
        $normalized_entity['_content_sync']['entity_dependencies'][$entity_type][] = $entity_type . "." . $parent
          ->bundle() . "." . $parent
          ->uuid();
      }
    }
    elseif (method_exists($entity, 'getParentId')) {
      $parent_id = $entity
        ->getParentId();
      if (($tmp = strstr($parent_id, ':')) !== false) {
        $parent_uuid = substr($tmp, 1);
        $parents = $storage
          ->loadByProperties([
          'uuid' => $parent_uuid,
        ]);
        $parent = !empty($parents) ? reset($parents) : null;
        if (!empty($parent) && !in_array($parent_uuid, $existing_parent_uuids)) {
          $normalized_entity['parent'][] = [
            'target_type' => $entity_type,
            'target_uuid' => $parent_uuid,
          ];
          $normalized_entity['_content_sync']['entity_dependencies'][$entity_type][] = $entity_type . "." . $parent
            ->bundle() . "." . $parent_uuid;
        }
      }
    }
  }
}