You are here

public function MenuLinkContentService::updateMenuLinkContentBundle in Menu Item Extras 8.2

@todo May be rewritten with states and batch for processing large data.

Overrides MenuLinkContentServiceInterface::updateMenuLinkContentBundle

File

src/Service/MenuLinkContentService.php, line 152

Class

MenuLinkContentService
Class MenuLinkContentHelper.

Namespace

Drupal\menu_item_extras\Service

Code

public function updateMenuLinkContentBundle() {

  // Retrieve existing field data.
  $tables = [
    "menu_link_content",
    "menu_link_content_data",
  ];
  $existing_data = [];
  foreach ($tables as $table) {

    // Get the old data.
    $existing_data[$table] = $this->connection
      ->select($table)
      ->fields($table)
      ->orderBy('id', 'ASC')
      ->execute()
      ->fetchAll(\PDO::FETCH_ASSOC);

    // Wipe it.
    $this->connection
      ->truncate($table)
      ->execute();
  }

  // Update definitions and scheme.
  // Process field storage definition changes.
  $this->entityTypeManager
    ->clearCachedDefinitions();
  $storage_definitions = $this->entityFieldManager
    ->getFieldStorageDefinitions('menu_link_content');
  $original_storage_definitions = $this->entityLastInstalledSchemaRepository
    ->getLastInstalledFieldStorageDefinitions('menu_link_content');
  $storage_definition = isset($storage_definitions['bundle']) ? $storage_definitions['bundle'] : NULL;
  $original_storage_definition = isset($original_storage_definitions['bundle']) ? $original_storage_definitions['bundle'] : NULL;
  $this->fieldStorageDefinitionListener
    ->onFieldStorageDefinitionUpdate($storage_definition, $original_storage_definition);

  // Restore the data.
  foreach ($tables as $table) {
    if (!empty($existing_data[$table])) {
      $insert_query = $this->connection
        ->insert($table)
        ->fields(array_keys(end($existing_data[$table])));
      foreach ($existing_data[$table] as $row) {
        $insert_query
          ->values(array_values($row));
      }
      $insert_query
        ->execute();
    }
  }
}