DevelHookCommand.php

Same filename in this branch
  1. 5.x src/Drush/Commands/DevelHookCommand.php

Namespace

Drupal\devel\Command

File

src/Command/DevelHookCommand.php

View source
<?php

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

use Drupal\Core\Extension\ModuleHandlerInterface;
use Drupal\Core\StringTranslation\StringTranslationTrait;
use Symfony\Component\Console\Attribute\Argument;
use Symfony\Component\Console\Attribute\AsCommand;
use Symfony\Component\Console\Attribute\Interact;
use Symfony\Component\Console\Attribute\Option;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Console\Style\SymfonyStyle;

/**
 * Lists the implementations of a hook and opens one in an editor.
 */
class DevelHookCommand {
  use CodeLocationTrait;
  use StringTranslationTrait;
  public const NAME = 'devel:hook';
  public function __construct(protected readonly ModuleHandlerInterface $moduleHandler) {
  }
  
  /**
   * Prompts for an implementation when none was given.
   */
  public function askForImplementation(InputInterface $input, OutputInterface $output) : void {
    $hook = $input->getArgument('hook');
    if (!$hook || $input->getArgument('implementation')) {
      return;
    }
    if ($implementations = $this->getImplementations($hook)) {
      $io = new SymfonyStyle($input, $output);
      $choice = $io->choice((string) $this->t('Select the hook implementation you wish to view.'), array_keys($implementations));
      $input->setArgument('implementation', $choice);
    }
  }
  
  /**
   * Lists the implementations of a hook, or opens one of them in an editor.
   */
  public function __invoke(InputInterface $input, OutputInterface $output, #[Argument('The name of the hook to explore.')] string $hook, #[Argument('The implementation to edit: a module name, or a function or Class::method name. Usually omitted.')] ?string $implementation = NULL, #[Option('A string of bash which launches your preferred text editor.')] string $editor = '${VISUAL-${EDITOR-vi}}') : int {
    $implementations = $this->getImplementations($hook);
    if ($implementations === []) {
      throw new \InvalidArgumentException('No implementations.');
    }
    // Without an implementation to edit, list them all.
    if ($implementation === NULL || $implementation === '') {
      foreach ($implementations as $info) {
        $output->writeln($info['file'] . ':' . $info['line']);
      }
      return Command::SUCCESS;
    }
    $info = $implementations[ltrim($implementation, '\\')] ?? array_find($implementations, static fn(array $info): bool => $info['module'] === $implementation);
    if ($info === NULL) {
      throw new \InvalidArgumentException(sprintf('%s does not implement hook_%s(). Implementations: %s', $implementation, $hook, implode(', ', array_keys($implementations))));
    }
    $this->edit($input, $output, $info, $editor);
    return Command::SUCCESS;
  }
  
  /**
   * Finds the implementations of a hook.
   *
   * @return array<string, array{module: string, name: string, file: string, line: int}>
   *   The implementations, keyed by function or Class::method name.
   */
  protected function getImplementations(string $hook) : array {
    $listeners = [];
    // Despite its name, invokeAllWith() only passes each implementation to the
    // callback. The hooks are collected here, never run.
    $this->moduleHandler
      ->invokeAllWith($hook, static function (callable $listener, string $module) use (&$listeners) : void {
      $listeners[] = [
        $module,
        $listener,
      ];
    });
    // Hooks in .install files, such as hook_install() and hook_update_N(), are
    // not registered as implementations. Find those by function name.
    include_once DRUPAL_ROOT . '/core/includes/install.inc';
    drupal_load_updates();
    foreach (array_keys($this->moduleHandler
      ->getModuleList()) as $module) {
      if (function_exists($module . '_' . $hook)) {
        $listeners[] = [
          $module,
          $module . '_' . $hook,
        ];
      }
    }
    $implementations = [];
    foreach ($listeners as [$module, $listener]) {
      $location = $this->locate($listener);
      $implementations[$location['name']] ??= [
        'module' => $module,
      ] + $location;
    }
    return $implementations;
  }

}

Classes

Title Deprecated Summary
DevelHookCommand Lists the implementations of a hook and opens one in an editor.