You are here

function auto_entitylabel_update_8201 in Automatic Entity Label 8.3

Same name and namespace in other branches
  1. 8.2 auto_entitylabel.install \auto_entitylabel_update_8201()

Split a single configuration into separate configs.

File

./auto_entitylabel.install, line 24
Install, update and uninstall functions for the Automatic Entity Labels.

Code

function auto_entitylabel_update_8201() {

  /** @var \Drupal\Core\Entity\EntityTypeManager $entity_type_manager */
  $entity_type_manager = \Drupal::entityTypeManager();

  /** @var \Drupal\Core\Config\Config $old_config */
  $old_config = \Drupal::configFactory()
    ->getEditable('auto_entitylabel.settings');
  $raw = $old_config
    ->getRawData();
  $entity_types = [];

  /** @var \Drupal\Core\Config\Entity\ConfigEntityType $entity_type */
  foreach ($entity_type_manager
    ->getDefinitions() as $entity_type_id => $entity_type) {
    if ($entity_type
      ->getLinkTemplate('auto-label')) {
      $entity_types[] = $entity_type_id;
    }
  }
  $setting_keys = [
    'status',
    'pattern',
    'php',
    'escape',
  ];
  $new_configs = [];
  foreach ($raw as $key => $value) {
    foreach ($entity_types as $type_id) {
      if (strpos($key, $type_id) === 0) {
        $key = substr($key, strlen($type_id) + 1);
        foreach ($setting_keys as $setting) {
          if (strpos($key, $setting) == strlen($key) - strlen($setting)) {
            $bundle = substr($key, 0, strlen($key) - strlen($setting) - 1);
            $new_configs[$type_id][$bundle][$setting] = $value;
          }
        }
        continue;
      }
    }
  }

  /** @var \Drupal\Core\Config\ConfigFactory $config_interface */
  $config_interface = \Drupal::service('config.factory');
  foreach ($new_configs as $type => $type_configs) {

    /** @var \Drupal\Core\Config\Entity\ConfigEntityTypeInterface $entityType */
    $entityType = $entity_type_manager
      ->getStorage($type)
      ->getEntityType();
    $prefix = $entityType
      ->getConfigPrefix();
    $type = $entity_type_manager
      ->getStorage($type)
      ->getEntityType()
      ->getProvider();
    foreach ($type_configs as $bundle => $settings) {
      $config_name = "auto_entitylabel.settings.{$type}.{$bundle}";
      $config = $config_interface
        ->getEditable($config_name);
      $config
        ->setData($settings);
      $config
        ->set('dependencies', [
        'config' => [
          "{$prefix}.{$bundle}",
        ],
      ]);
      $config
        ->save();
    }
  }
  $old_config
    ->delete();
}