You are here

public function ContentLoaderBase::importEntity in YAML Content 8.2

Load an entity from a loaded import data outline.

Parameters

array $content_data: The loaded array of content data to populate into this entity.

Required keys:

  • `entity`: The entity type machine name.

Return value

\Drupal\Core\Entity\EntityInterface The built and imported content entity.

Throws

\Exception

3 calls to ContentLoaderBase::importEntity()
ContentLoaderBase::importFieldItem in src/ContentLoader/ContentLoaderBase.php
Process import data for an individual field list item value.
ContentLoaderBase::loadContent in src/ContentLoader/ContentLoaderBase.php
Load all demo content for a set of parsed data.
ProcessedContentLoader::importEntity in src/ContentLoader/ProcessedContentLoader.php
Load an entity from a loaded import data outline.
1 method overrides ContentLoaderBase::importEntity()
ProcessedContentLoader::importEntity in src/ContentLoader/ProcessedContentLoader.php
Load an entity from a loaded import data outline.

File

src/ContentLoader/ContentLoaderBase.php, line 182

Class

ContentLoaderBase
A base ContentLoader implementation to be extended by new content loaders.

Namespace

Drupal\yaml_content\ContentLoader

Code

public function importEntity(array $content_data) {

  // @todo Validate entity information for building.
  if (!isset($content_data['entity'])) {
    throw new \Exception('An entity type is required in the "entity" key.');
  }
  else {
    $entity_type = $content_data['entity'];
  }
  if (!$this->entityTypeManager
    ->hasDefinition($entity_type)) {

    // @todo Update this to use `t()`.
    throw new \Exception(sprintf('Invalid entity type: %s', $entity_type));
  }

  // Build the basic entity structure.
  $entity = $this
    ->buildEntity($entity_type, $content_data);

  // @todo Break this out into `$this->importEntityFields()`.
  // Import the entity fields if applicable.
  if ($entity instanceof FieldableEntityInterface) {
    $field_definitions = $entity
      ->getFieldDefinitions();

    // Iterate across each field value in the import content.
    foreach (array_intersect_key($content_data, $field_definitions) as $field_name => $field_data) {

      // Ensure data is wrapped as an array to handle field values as a list.
      if (!is_array($field_data)) {
        $field_data = [
          $field_data,
        ];
      }

      // Dispatch field import event prior to populating fields.
      $field_import_event = new FieldImportEvent($this, $entity, $field_definitions[$field_name], $field_data);
      $this->dispatcher
        ->dispatch(YamlContentEvents::IMPORT_FIELD, $field_import_event);
      $this
        ->importEntityField($field_data, $entity, $field_definitions[$field_name]);
    }
  }
  return $entity;
}