component_library-1.0.x-dev/component_library.post_update.php

component_library.post_update.php
<?php // phpcs:ignore Drupal.Commenting.FileComment.Missing

declare(strict_types=1);

/**
 * @file
 * Post update functions for Component library module.
 */

use Drupal\component_library\CodeMirrorSettings;
use Drupal\Core\Database\Database;
use Drupal\component_library\Entity\ComponentLibraryAsset;

/**
 * Migrate assets to new files data model.
 */
function component_library_post_update_asset_files(&$sandbox): void {
  foreach (ComponentLibraryAsset::loadMultiple() as $id => $asset) {
    $files = [];
    if (!empty($asset->css)) {
      _migrate_files_to_new_data_model($asset->css, $files, $id, 'css');
    }
    if (!empty($asset->js)) {
      _migrate_files_to_new_data_model($asset->js, $files, $id, 'js');
    }
    $asset->setFiles($files);
    $files_with_paths = $asset->getFiles();
    $asset->setFiles($files_with_paths);
    $asset->save();
  }
}

/**
 * Helper to migrate asset files data model.
 */
function _migrate_files_to_new_data_model(array $old_files, array &$new_files, string $id, $type) {
  $count = 0;
  foreach ($old_files as $file) {
    $new_files[] = [
      'name' => \sprintf('%s%s', str_replace('_', '-', $id), $count > 0 ? '-' . $count : ''),
      'type' => $type,
      'code' => $file['code'],
    ];
    $count++;
  }
}

/**
 * Rename entity prefix for pattens and variations.
 */
function component_library_post_update_entity_prefix(&$sandbox = []): void {
  $config_to_update = [
    'component_library.component_library_pattern' => 'component_library.pattern',
    'component_library.component_library_variant' => 'component_library.variant',
  ];
  $connection = Database::getConnection();
  foreach ($config_to_update as $old_prefix => $new_prefix) {
    $query = $connection->select('config', 'c')
      ->fields('c', ['name', 'data'])
      ->condition('collection', '')
      ->condition('name', "$old_prefix.%", 'LIKE');
    foreach ($query->execute()->fetchAllKeyed() as $name => $data) {
      $data = unserialize($data, ['allowed_classes' => FALSE]);
      foreach ($data['dependencies'] as $type => $dependencies) {
        foreach ($dependencies as $key => $dependency) {
          $data['dependencies'][$type][$key] = str_replace('component_library.component_library_pattern', 'component_library.pattern', $dependency);
        }
      }
      $connection->update('config')
        ->condition('collection', '')
        ->condition('name', $name)
        ->fields([
          'name' => \str_replace($old_prefix, $new_prefix, $name),
          'data' => serialize($data),
        ])->execute();
    }
  }
}

/**
 * Enable CSS, JS, and TWIG CodeMirror support.
 */
function component_library_post_update_enable_codemirror_languages(&$sandbox) {
  \Drupal::classResolver(CodeMirrorSettings::class)->enableLanguages();
}

Главная | Обратная связь

drupal hosting | друпал хостинг | it patrol .inc