CodeLocationTrait.php

Namespace

Drupal\devel\Command

File

src/Command/CodeLocationTrait.php

View source
<?php

declare (strict_types=1);
namespace Drupal\devel\Command;

use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Process\Process;

/**
 * Locates the source code of callables and opens it in an editor.
 */
trait CodeLocationTrait {
  
  /**
   * Describes where a callable is defined.
   *
   * @return array{name: string, file: string, line: int}
   *   The function or Class::method name, its file and its first line.
   */
  protected function locate(callable $callable) : array {
    $reflection = new \ReflectionFunction(\Closure::fromCallable($callable));
    is_callable($callable, FALSE, $name);
    if ($callable instanceof \Closure) {
      $name = $reflection->getName();
    }
    return [
      'name' => $name,
      'file' => (string) $reflection->getFileName(),
      'line' => (int) $reflection->getStartLine(),
    ];
  }
  
  /**
   * Opens a file in the user's editor.
   *
   * An editor needs a terminal. Without one, the location is printed instead.
   *
   * @param \Symfony\Component\Console\Input\InputInterface $input
   *   The input.
   * @param \Symfony\Component\Console\Output\OutputInterface $output
   *   The output.
   * @param array{file: string, line: int} $location
   *   A location, as returned by ::locate().
   * @param string $editor
   *   A string of bash which launches a text editor.
   */
  protected function edit(InputInterface $input, OutputInterface $output, array $location, string $editor) : void {
    if (!$input->isInteractive() || !Process::isTtySupported()) {
      $output->writeln($location['file'] . ':' . $location['line']);
      return;
    }
    $process = Process::fromShellCommandline($editor . ' "${:DEVEL_FILE}"', timeout: NULL);
    $process->setTty(TRUE);
    $process->mustRun(env: [
      'DEVEL_FILE' => $location['file'],
    ]);
  }

}

Traits

Title Deprecated Summary
CodeLocationTrait Locates the source code of callables and opens it in an editor.