You are here

public function Config::importFile in Helper 8

Import a single configuration file.

Parameters

string $uri: The path to the file.

string $contents: Optional manual contents of the file.

Throws

\RuntimeException If unable to decode YAML from file.

\Drupal\Core\Entity\EntityStorageException In unable to save the config.

1 call to Config::importFile()
Config::importDirectory in src/Config.php
Import a directory containing configuration files.

File

src/Config.php, line 78

Class

Config
Provides helper for working with configuration.

Namespace

Drupal\helper

Code

public function importFile($uri, $contents = NULL) {
  if (!isset($contents) && !($contents = @file_get_contents($uri))) {
    throw new \RuntimeException("Unable to read file {$uri}.");
  }
  $data = Yaml::decode($contents);
  if (!is_array($data)) {
    throw new \RuntimeException("Unable to decode YAML from {$uri}.");
  }
  $this->logger
    ->notice('Importing @uri.', [
    '@uri' => $uri,
  ]);
  $config_name = basename($uri, '.yml');
  $entity_type_id = $this->configManager
    ->getEntityTypeIdByName($config_name);
  if ($entity_type_id) {
    $entity_storage = $this
      ->getStorage($entity_type_id);
    $entity_id = $this
      ->getEntityId($entity_storage, $config_name);
    $entity_type = $entity_storage
      ->getEntityType();
    $id_key = $entity_type
      ->getKey('id');
    $data[$id_key] = $entity_id;

    /** @var \Drupal\Core\Config\Entity\ConfigEntityInterface $entity */
    $entity = $entity_storage
      ->create($data);
    if ($existing_entity = $entity_storage
      ->load($entity_id)) {
      $entity
        ->set('uuid', $existing_entity
        ->uuid())
        ->enforceIsNew(FALSE);
    }
    $entity_storage
      ->save($entity);
  }
  else {
    $this->configFactory
      ->getEditable($config_name)
      ->setData($data)
      ->save();
  }
}