You are here

public function RectorProcessor::runRector in Upgrade Rector 8

Run rector on a given extension.

Parameters

\Drupal\Core\Extension\Extension $extension: Extension to run rector on.

Return value

bool TRUE if successful, FALSE otherwise. The results are saved into the result storage either way.

File

src/RectorProcessor.php, line 90

Class

RectorProcessor
Runs rector and processes rector results.

Namespace

Drupal\upgrade_rector

Code

public function runRector(Extension $extension) {
  $vendor_path = $this
    ->findVendorPath();
  if (empty($vendor_path)) {
    $this->logger
      ->error('Rector executable not found. This would happen if the composer dependencies were not installed. Did you use composer to install the module?');
    return FALSE;
  }
  if (function_exists('file_directory_temp')) {

    // This is fallback code for 8.7.x and below. It's not called on later
    // versions, so we don't nee to "fix" it.
    // @noRector
    // @phpstan-ignore-next-line
    $system_temporary = file_directory_temp();
  }
  else {
    $system_temporary = $this->fileSystem
      ->getTempDirectory();
  }
  $temporary_directory = realpath($system_temporary) . '/upgrade_rector';
  $success = $this->fileSystem
    ->prepareDirectory($temporary_directory, FileSystemInterface::CREATE_DIRECTORY | FileSystemInterface::MODIFY_PERMISSIONS);
  if (!$success) {
    $this->rectorResults
      ->set($extension
      ->getName(), sprintf('Unable to create temporary directory at %s.', $temporary_directory));
    $this->logger
      ->error('Unable to create temporary directory at %directory.', [
      '%directory' => $temporary_directory,
    ]);
    return FALSE;
  }
  $module_path = DRUPAL_ROOT . '/' . drupal_get_path('module', 'upgrade_rector');
  $config = file_get_contents($module_path . '/rector-config-template.php');
  $config = str_replace('$vendor_dir', "'" . $vendor_path . "'", $config);

  // Replace backslash for Windows compatibility.
  $config = str_replace('$drupal_root', "'" . str_replace('\\', '/', DRUPAL_ROOT) . "'", $config);
  $config_path = $temporary_directory . '/rector-config.php';
  $success = file_put_contents($config_path, $config);
  if (!$success) {
    $this->rectorResults
      ->set($extension
      ->getName(), sprintf('Unable to write rector configuration to %s.', $config_path));
    $this->logger
      ->error('Unable to write rector configuration to %file.', [
      '%file' => $config_path,
    ]);
    return FALSE;
  }
  $output = [];
  $cmd = 'cd ' . dirname($vendor_path) . ' && ' . $vendor_path . '/bin/rector process ' . DRUPAL_ROOT . '/' . $extension
    ->getPath() . ' --dry-run --config=' . $config_path . ' 2>&1';
  exec($cmd, $output);
  $output = join("\n", $output);
  $this->rectorResults
    ->set($extension
    ->getName(), $output);
  return strpos($output, '[OK] Rector is done!');
}