You are here

public function Importer::import in Default Content Deploy 8

Import to entity.

Throws

\Drupal\Component\Plugin\Exception\InvalidPluginDefinitionException

\Drupal\Component\Plugin\Exception\PluginNotFoundException

\Drupal\Core\Entity\EntityStorageException

File

src/Importer.php, line 286

Class

Importer
A service for handling import of default content.

Namespace

Drupal\default_content_deploy

Code

public function import() {
  $files = $this->dataToImport;
  if (PHP_SAPI === 'cli') {
    $root_user = $this->entityTypeManager
      ->getStorage('user')
      ->load(1);
    $this->accountSwitcher
      ->switchTo($root_user);
  }

  // All entities with entity references will be imported two times to ensure
  // that all entity references are present and valid. Path aliases will be
  // imported last to have a chance to rewrite them to the new ids of newly
  // created entities.
  for ($i = 0; $i <= 2; $i++) {
    foreach ($files as $uuid => &$file) {
      if ($file['status'] !== 'skip') {
        $entity_type = $file['entity_type_id'];
        if ($i !== 2 && $entity_type === 'path_alias') {
          continue;
        }
        $this->linkManager
          ->setLinkDomain($this
          ->getLinkDomain($file));
        $class = $this->entityTypeManager
          ->getDefinition($entity_type)
          ->getClass();
        $this
          ->preDenormalize($file, $entity_type);

        /** @var \Drupal\Core\Entity\ContentEntityInterface $entity */
        $entity = $this->serializer
          ->denormalize($file['data'], $class, 'hal_json', [
          'request_method' => 'POST',
        ]);
        $entity
          ->enforceIsNew($file['is_new']);
        $entity
          ->save();
        $this->entityIdLookup[$uuid] = $entity
          ->id();
        if (empty($file['references']) || $i === 1) {

          // Don't handle entities without references twice. Don't handle
          // entities with references again in the third run for path aliases.
          unset($files[$uuid]);
        }
        else {

          // In the second run new entities should be updated.
          $file['status'] = 'update';
          $file['is_new'] = FALSE;
          $file['data'][$file['key_id']][0]['value'] = $entity
            ->id();
        }
      }
    }
    unset($file);
  }

  // @todo is this still needed?
  $this->linkManager
    ->setLinkDomain(FALSE);
  if (PHP_SAPI === 'cli') {
    $this->accountSwitcher
      ->switchBack();
  }
}