function EntityCreate::apply

Same name in other branches
  1. 10 core/lib/Drupal/Core/Config/Action/Plugin/ConfigAction/EntityCreate.php \Drupal\Core\Config\Action\Plugin\ConfigAction\EntityCreate::apply()

Overrides ConfigActionPluginInterface::apply

File

core/lib/Drupal/Core/Config/Action/Plugin/ConfigAction/EntityCreate.php, line 51

Class

EntityCreate
@internal This API is experimental.

Namespace

Drupal\Core\Config\Action\Plugin\ConfigAction

Code

public function apply(string $configName, mixed $value) : void {
    if (!is_array($value)) {
        throw new ConfigActionException(sprintf("The value provided to create %s must be an array", $configName));
    }
    
    /** @var \Drupal\Core\Config\Entity\ConfigEntityInterface|null $entity */
    $entity = $this->configManager
        ->loadConfigEntityByName($configName);
    if ($this->exists
        ->returnEarly($configName, $entity)) {
        return;
    }
    $entity_type_manager = $this->configManager
        ->getEntityTypeManager();
    $entity_type_id = $this->configManager
        ->getEntityTypeIdByName($configName);
    if ($entity_type_id === NULL) {
        throw new ConfigActionException(sprintf("Cannot determine a config entity type from %s", $configName));
    }
    
    /** @var \Drupal\Core\Config\Entity\ConfigEntityTypeInterface $entity_type */
    $entity_type = $entity_type_manager->getDefinition($entity_type_id);
    $id = substr($configName, strlen($entity_type->getConfigPrefix()) + 1);
    $entity_type_manager->getStorage($entity_type->id())
        ->create($value + [
        $entity_type->getKey('id') => $id,
    ])
        ->save();
}

Buggy or inaccurate documentation? Please file an issue. Need support? Need help programming? Connect with the Drupal community.