[Drupal 7] PHP script to rename node type machine name

The following PHP script leverages Drush to rename a Drupal 7 machine name and important related database table entries, in preparation for migration to Drupal 8.

Completion Date
PHP Logo
Platform(s)/Language(s)
Code Snippet
<?php
 
/**
 * @file
 * Pre-Migration D7 rename entity types.
 *
 * Rename entity type `old_machine_name` to `new_machine_name` in D7 db.
 *
 * References:
 * - Drupal 7 function: node_type_form_submit()
 * - http://data.agaric.com/node/3907
 *
 *  Run command: `drush scr migrate_pre_d7_rename_entity_types.php`.
 */
 
echo "Begin: Rename entity types\n";
 
$old_type = 'old_machine_name';
$new_type = 'new_machine_name';
 
try {
  if ($type = node_type_load($old_type)) {
    $type->type = $new_type;
    $type->old_type = $type->orig_type;
 
    // Saving the content type after saving the variables allows modules to act
    // on those variables via hook_node_type_insert().
    $status = node_type_save($type);
 
    node_types_rebuild();
    menu_rebuild();
 
    if ($status == SAVED_UPDATED) {
      echo "\n  " . t('The content type @name has been updated.', ['@name' => $type->name]);
    }
 
    if (!empty($type->old_type) && $type->old_type != $type->type) {
      $update_count = node_type_update_nodes($old_type, $new_type);
      if ($update_count) {
        echo "\n  " . format_plural(
          $update_count,
          'Changed the content type of 1 node from @old-type to @type.',
          'Changed the content type of @count nodes from @old-type to @type.',
          ['@old-type' => $old_type, '@type' => $new_type]
        );
      }
    }
  }
 
  $table = 'nodequeue_types';
  if (db_table_exists($table)) {
    $query = db_select($table, 't')
      ->fields('t')
      ->condition('type', $old_type);
    $results = $query->execute()->fetchAll();
    if ($num = count($results)) {
      echo "\n  Changing bundle in $num `$table` records from '$old_type' to '$new_type'.";
      $num_updated = db_update($table)
        ->fields(['type' => $new_type])
        ->condition('type', $old_type)
        ->execute();
      echo "\n  - Updated $num_updated records.";
    }
  }
 
  $table = 'field_group';
  if (db_table_exists($table)) {
    $query = db_select($table, 't')
      ->fields('t')
      ->condition('identifier', '%' . $old_type . '%', 'LIKE');
    $results = $query->execute()->fetchAll();
    if ($num = count($results)) {
      echo "\n  Changing bundle in `$table` table records from '$old_type' to '$new_type'.";
      $num_updated = 0;
      foreach ($results as $result) {
        $string = str_replace($old_type, $new_type, $result->identifier);
        $num_updated += db_update($table)
          ->fields(['identifier' => $string])
          ->condition('id', $result->id)
          ->execute();
      }
      echo "\n  - Updated $num_updated records.";
    }
  }
 
  $table = 'views_display';
  if (db_table_exists($table)) {
    $query = db_select($table, 't')
      ->fields('t')
      ->condition('display_options', '%' . $old_type . '%', 'LIKE');
    $results = $query->execute()->fetchAll();
    $num_updated = 0;
    if ($num = count($results)) {
      echo "\n  Changing bundle in `$table` table records from '$old_type' to '$new_type'.";
      foreach ($results as $result) {
        $display_options = unserialize($result->display_options);
        $key_changed = rename_array_key($display_options, $old_type, $new_type);
        $value_changed = update_array_value($display_options, $old_type, $new_type);
        if ($key_changed || $value_changed) {
          $num_updated += db_update($table)
            ->fields(['display_options' => serialize($display_options)])
            ->condition('vid', $result->vid)
            ->condition('id', $result->id)
            ->execute();
        }
      }
      echo "\n  - Updated $num_updated records.";
    }
  }
 
  $table = 'field_config';
  if (db_table_exists($table)) {
    $query = db_select($table, 't')
      ->fields('t')
      ->condition('data', '%blog_post%', 'LIKE');
    $results = $query->execute()->fetchAll();
    foreach ($results as $result) {
      $data = unserialize($result->data);
      $changed_key = rename_array_key($data, 'blog_post', 'blog');
      $changed_value = update_array_value($data, 'blog_post', 'blog');
      if ($changed_key || $changed_value) {
        echo "\n  Updating $table data in `$result->field_name`.";
        $result->data = serialize($data);
        $num_updated = db_update($table)
          ->fields((array) $result)
          ->condition('id', $result->id)
          ->execute();
        echo "\n  - Updated $num_updated records.";
      }
    }
  }
 
  $table = 'variable';
  if (db_table_exists($table)) {
    $query = db_select($table, 't')
      ->fields('t')
      ->condition('name', '%_blog_post', 'LIKE');
    $results = $query->execute()->fetchAll();
    echo "\n  Deleting records from table `$table`.";
    foreach ($results as $result) {
      variable_del($result->name);
    }
    echo "\n  - Deleted " . count($results) . " records.\n";
  }
 
}
catch (Exception $e) {
  echo 'D7 exception: ', $e->getMessage(), "\n";
  exit(1);
}
 
echo "\nCompleted: D7 Pre-Migrate, Rename entity types\n";
 
/**
 * Recursively change all keys of a given name in a multi-dimensional array.
 *
 * Also, preserve original key order. References:
 * - https://stackoverflow.com/questions/13233405/
 *
 * @param array &$data
 *   The data.
 * @param string $old_key
 *   The old key.
 * @param string $new_key
 *   The new key.
 *
 * @return bool
 *   True if the rename was successful or False if the old key cannot be found
 *   or the new key already exists.
 */
function rename_array_key(array &$data, $old_key, $new_key) {
  $result = FALSE;
 
  if (!empty($data)) {
    if (array_key_exists($old_key, $data)) {
      $keys = array_keys($data);
      $keys[array_search($old_key, array_map('strval', $keys))] = $new_key;
      $data = array_combine($keys, $data);
      $result = TRUE;
    }
 
    // Recursively search each sub-array for the old key & update it if found.
    foreach ($data as $sub_key => $sub_data) {
      if (is_array($sub_data)) {
        if (rename_array_key($sub_data, $old_key, $new_key)) {
          $data[$sub_key] = $sub_data;
          $result = TRUE;
        }
      }
    }
  }
 
  return $result;
}
 
/**
 * Recursively update all array entries of a given value to a new value.
 *
 * @param array &$data
 *   The data.
 * @param mixed $old_val
 *   The old key.
 * @param mixed $new_val
 *   The new key.
 *
 * @return bool
 *   True if the rename was successful or False if the old key cannot be found
 *   or the new key already exists.
 */
function update_array_value(array &$data, $old_val, $new_val) {
  $result = FALSE;
 
  foreach ($data as $key => $val) {
    if ($val === $old_val) {
      $data[$key] = $new_val;
      echo "  - updating value for $key from $old_val to $new_val\n";
      $result = TRUE;
    }
    // Recursively search each sub-array for the old value & update it if found.
    if (is_array($val)) {
      if (update_array_value($val, $old_val, $new_val)) {
        $data[$key] = $val;
        $result = TRUE;
      }
    }
  }
 
  return $result;
}

Drupal Association Individual Member      Drupal Association Individual Member      #DrupalCares Supporter      Acquia Certified Site Builder