DevelHooks.php

Namespace

Drupal\devel\Hook

File

src/Hook/DevelHooks.php

View source
<?php

namespace Drupal\devel\Hook;

use Drupal\Core\Cache\CacheableMetadata;
use Drupal\Core\Config\ConfigFactoryInterface;
use Drupal\Core\Database\Query\AlterableInterface;
use Drupal\Core\DependencyInjection\ClassResolverInterface;
use Drupal\Core\Entity\EntityInterface;
use Drupal\Core\Extension\ModuleHandlerInterface;
use Drupal\Core\Extension\Requirement\RequirementSeverity;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Hook\Attribute\Hook;
use Drupal\Core\Menu\LocalTaskDefault;
use Drupal\Core\Render\Element;
use Drupal\Core\Routing\RouteMatchInterface;
use Drupal\Core\Session\AccountInterface;
use Drupal\Core\StringTranslation\StringTranslationTrait;
use Drupal\Core\StringTranslation\TranslatableMarkup;
use Drupal\Core\Url;
use Drupal\devel\DevelDumperManagerInterface;
use Drupal\devel\EntityTypeInfo;
use Drupal\devel\ToolbarHandler;
use Symfony\Component\DependencyInjection\Attribute\Autowire;

/**
 * Hook implementations for devel.
 */
class DevelHooks {
  use StringTranslationTrait;
  public function __construct(protected readonly ClassResolverInterface $classResolver, protected readonly ModuleHandlerInterface $moduleHandler, protected readonly AccountInterface $currentUser, protected readonly ConfigFactoryInterface $configFactory, #[Autowire(service: 'devel.dumper')] protected readonly DevelDumperManagerInterface $dumper) {
  }
  
  /**
   * Implements hook_help().
   */
  public function help($route_name, RouteMatchInterface $route_match) : ?string {
    switch ($route_name) {
      case 'help.page.devel':
        $output = '<h3>' . $this->t('About') . '</h3>';
        $output .= '<p>' . $this->t('The Devel module provides a suite of modules containing fun for module developers and themers. For more information, see the <a href=":url">online documentation for the Devel module</a>.', [
          ':url' => 'https://www.drupal.org/docs/contributed-modules/devel',
        ]) . '</p>';
        $output .= '<h3>' . $this->t('Uses') . '</h3>';
        $output .= '<dl>';
        $output .= '<dt>' . $this->t('Inspecting Service Container') . '</dt>';
        $output .= '<dd>' . $this->t('The module allows you to inspect Services and Parameters registered in the Service Container. You can see those informations on <a href=":url">Container info</a> page.', [
          ':url' => Url::fromRoute('devel.container_info.service')->toString(),
        ]) . '</dd>';
        $output .= '<dt>' . $this->t('Inspecting Routes') . '</dt>';
        $output .= '<dd>' . $this->t('The module allows you to inspect routes information, gathering all routing data from <em>.routing.yml</em> files and from classes which subscribe to the route build/alter events. You can see those informations on <a href=":url">Routes info</a> page.', [
          ':url' => Url::fromRoute('devel.route_info')->toString(),
        ]) . '</dd>';
        $output .= '<dt>' . $this->t('Inspecting Events') . '</dt>';
        $output .= '<dd>' . $this->t('The module allow you to inspect listeners registered in the event dispatcher. You can see those informations on <a href=":url">Events info</a> page.', [
          ':url' => Url::fromRoute('devel.event_info')->toString(),
        ]) . '</dd>';
        $output .= '</dl>';
        return $output;
      case 'devel.container_info.service':
      case 'devel.container_info.parameter':
        return '<p>' . $this->t('Displays Services and Parameters registered in the Service Container. For more informations on the Service Container, see the <a href=":url">Symfony online documentation</a>.', [
          ':url' => 'http://symfony.com/doc/current/service_container.html',
        ]) . '</p>';
      case 'devel.route_info':
        return '<p>' . $this->t('Displays registered routes for the site. For a complete overview of the routing system, see the <a href=":url">online documentation</a>.', [
          ':url' => 'https://www.drupal.org/docs/drupal-apis/routing-system',
        ]) . '</p>';
      case 'devel.event_info':
        return '<p>' . $this->t('Displays events and listeners registered in the event dispatcher. For a complete overview of the event system, see the <a href=":url">Symfony online documentation</a>.', [
          ':url' => 'http://symfony.com/doc/current/components/event_dispatcher.html',
        ]) . '</p>';
      case 'devel.reinstall':
        $output = '<p>' . $this->t('<strong>Warning</strong> - will delete your module tables and configuration.') . '</p>';
        $output .= '<p>' . $this->t('Uninstall and then install the selected modules. <code>hook_uninstall()</code> and <code>hook_install()</code> will be executed and the schema version number will be set to the most recent update number.') . '</p>';
        return $output;
      case 'devel/session':
        return '<p>' . $this->t('Here are the contents of your <code>$_SESSION</code> variable.') . '</p>';
      case 'devel.state_system_page':
        return '<p>' . $this->t('This is a list of state variables and their values. For more information read online documentation of <a href=":documentation">State API in Drupal 8</a>.', [
          ':documentation' => "https://www.drupal.org/docs/develop/drupal-apis/state-api",
        ]) . '</p>';
      case 'devel.layout_info':
        return '<p>' . $this->t('Displays layouts available to the site. For a complete overview of the layout system, see the <a href=":url">Layout API documentation</a>.', [
          ':url' => 'https://www.drupal.org/docs/drupal-apis/layout-api',
        ]) . '</p>';
    }
    return NULL;
  }
  
  /**
   * Implements hook_runtime_requirements().
   */
  public function runtimeRequirements() : array {
    // To understand the reasons why this message is marked as info see
    // https://www.drupal.org/node/2834400.
    $requirements['devel'] = [
      'title' => $this->t('Devel module enabled'),
      'description' => $this->t("The Devel module provides access to internal debugging information; therefore it's recommended to disable this module on sites in production."),
      'severity' => RequirementSeverity::Info,
    ];
    return $requirements;
  }
  
  /**
   * Implements hook_entity_type_alter().
   */
  public function entityTypeAlter(array &$entity_types) : void {
    $this->classResolver
      ->getInstanceFromDefinition(EntityTypeInfo::class)
      ->entityTypeAlter($entity_types);
  }
  
  /**
   * Implements hook_entity_operation().
   */
  public function entityOperation(EntityInterface $entity, CacheableMetadata $cacheability) : array {
    return $this->classResolver
      ->getInstanceFromDefinition(EntityTypeInfo::class)
      ->entityOperation($entity, $cacheability);
  }
  
  /**
   * Implements hook_toolbar().
   */
  public function toolbar() : array {
    return $this->classResolver
      ->getInstanceFromDefinition(ToolbarHandler::class)
      ->toolbar();
  }
  
  /**
   * Implements hook_menu_links_discovered_alter().
   */
  public function menuLinksDiscoveredAlter(array &$links) : void {
    // Conditionally add the Layouts info menu link.
    if ($this->moduleHandler
      ->moduleExists('layout_discovery')) {
      $links['devel.layout_info'] = [
        'title' => new TranslatableMarkup('Layouts Info'),
        'route_name' => 'devel.layout_info',
        'description' => new TranslatableMarkup('Overview of layouts available to the site.'),
        'menu_name' => 'devel',
      ];
    }
  }
  
  /**
   * Implements hook_local_tasks_alter().
   */
  public function localTasksAlter(array &$local_tasks) : void {
    if ($this->moduleHandler
      ->moduleExists('toolbar')) {
      $local_tasks['devel.toolbar.settings_form'] = [
        'title' => 'Toolbar Settings',
        'base_route' => 'devel.admin_settings',
        'route_name' => 'devel.toolbar.settings_form',
        'class' => LocalTaskDefault::class,
        'options' => [],
      ];
    }
  }
  
  /**
   * Implements hook_page_attachments_alter().
   */
  public function pageAttachmentsAlter(array &$attachments) : void {
    if ($this->currentUser
      ->hasPermission('access devel information') && $this->configFactory
      ->get('devel.settings')
      ->get('page_alter')) {
      $this->dumper
        ->message(input: $attachments, name: 'attachments');
    }
  }
  
  /**
   * Implements hook_form_FORM_ID_alter() for user_admin_permissions.
   *
   * Adds mouse-over hints on the Permissions page to display
   * language-independent machine names and module base names.
   *
   * @see \Drupal\user\Form\UserPermissionsForm::buildForm()
   */
  public function formUserAdminPermissionsAlter(array &$form, FormStateInterface $form_state) : void {
    if ($this->currentUser
      ->hasPermission('access devel information') && $this->configFactory
      ->get('devel.settings')
      ->get('raw_names')) {
      foreach (Element::children($form['permissions']) as $key) {
        if (isset($form['permissions'][$key][0])) {
          $form['permissions'][$key][0]['#wrapper_attributes']['title'] = $key;
        }
        elseif (isset($form['permissions'][$key]['description'])) {
          $form['permissions'][$key]['description']['#wrapper_attributes']['title'] = $key;
        }
      }
    }
  }
  
  /**
   * Implements hook_form_FORM_ID_alter() for system_modules.
   *
   * Adds mouse-over hints on the Modules page to display module base names.
   *
   * @see \Drupal\system\Form\ModulesListForm::buildForm()
   */
  public function formSystemModulesAlter(array &$form, FormStateInterface $form_state) : void {
    if ($this->currentUser
      ->hasPermission('access devel information') && $this->configFactory
      ->get('devel.settings')
      ->get('raw_names') && isset($form['modules']) && is_array($form['modules'])) {
      foreach (Element::children($form['modules']) as $group) {
        if (is_array($form['modules'][$group])) {
          foreach (Element::children($form['modules'][$group]) as $key) {
            if (isset($form['modules'][$group][$key]['name']['#markup'])) {
              $form['modules'][$group][$key]['name']['#markup'] = '<span title="' . $key . '">' . $form['modules'][$group][$key]['name']['#markup'] . '</span>';
            }
          }
        }
      }
    }
  }
  
  /**
   * Implements hook_query_TAG_alter() for the 'debug' tag.
   *
   * Makes debugging entity query much easier.
   *
   * Example usage:
   *
   * @code
   * $query = \Drupal::entityQuery('node');
   * $query->condition('status', NODE_PUBLISHED);
   * $query->addTag('debug');
   * $query->execute();
   * @endcode
   */
  public function queryDebugAlter(AlterableInterface $query) : void {
    if (!$query->hasTag('debug-semaphore')) {
      $query->addTag('debug-semaphore');
      // phpcs:disable Drupal.Functions.DiscouragedFunctions
      // @phpstan-ignore discouragedFunctions.discouragedFunctionCalled
      dpq($query);
      // phpcs:enable
    }
  }

}

Classes

Title Deprecated Summary
DevelHooks Hook implementations for devel.