You are here

public function Exporter::exportContentWithReferences in Default Content for D8 8

Same name and namespace in other branches
  1. 2.0.x src/Exporter.php \Drupal\default_content\Exporter::exportContentWithReferences()

Exports a single entity and all its referenced entity.

Parameters

string $entity_type_id: The entity type ID.

mixed $entity_id: The entity ID to export.

Return value

string[][] The serialized entities keyed by entity type and UUID.

Overrides ExporterInterface::exportContentWithReferences

File

src/Exporter.php, line 167

Class

Exporter
A service for handling import of default content.

Namespace

Drupal\default_content

Code

public function exportContentWithReferences($entity_type_id, $entity_id) {
  $storage = $this->entityTypeManager
    ->getStorage($entity_type_id);
  $entity = $storage
    ->load($entity_id);
  if (!$entity) {
    throw new \InvalidArgumentException(sprintf('Entity "%s" with ID "%s" does not exist', $entity_type_id, $entity_id));
  }
  if (!$entity instanceof ContentEntityInterface) {
    throw new \InvalidArgumentException(sprintf('Entity "%s" with ID "%s" is not a content entity', $entity_type_id, $entity_id));
  }
  $entities = [
    $entity
      ->uuid() => $entity,
  ];
  $entities = $this
    ->getEntityReferencesRecursive($entity, 0, $entities);
  if ($this
    ->isCli()) {
    $root_user = $this->entityTypeManager
      ->getStorage('user')
      ->load(1);
    $this->accountSwitcher
      ->switchTo($root_user);
  }
  $this->linkManager
    ->setLinkDomain($this->linkDomain);

  // Serialize all entities and key them by entity TYPE and uuid.
  $serialized_entities_per_type = [];
  foreach ($entities as $entity) {
    $serialized_entities_per_type[$entity
      ->getEntityTypeId()][$entity
      ->uuid()] = $this->serializer
      ->serialize($entity, 'hal_json', [
      'json_encode_options' => JSON_PRETTY_PRINT,
    ]);
  }

  // Reset the link domain and the current user, if needed.
  $this->linkManager
    ->setLinkDomain(FALSE);
  if ($this
    ->isCli()) {
    $this->accountSwitcher
      ->switchBack();
  }
  return $serialized_entities_per_type;
}