5 * This module holds functions useful for Drupal development.
9 define('DEVEL_ERROR_HANDLER_NONE', 0);
10 define('DEVEL_ERROR_HANDLER_STANDARD', 1);
11 define('DEVEL_ERROR_HANDLER_BACKTRACE_KINT', 2);
12 define('DEVEL_ERROR_HANDLER_BACKTRACE_DPM', 4);
14 define('DEVEL_MIN_TEXTAREA', 50);
16 use Drupal\comment\CommentInterface;
17 use Drupal\Core\Database\Database;
18 use Drupal\Core\Database\Query\AlterableInterface;
19 use Drupal\Core\Entity\EntityInterface;
20 use Drupal\Core\Form\FormStateInterface;
21 use Drupal\Core\Logger\RfcLogLevel;
22 use Drupal\Core\Menu\LocalTaskDefault;
23 use Drupal\Core\Render\Element;
24 use Drupal\Core\Routing\RouteMatchInterface;
26 use Drupal\Core\Utility\Error;
27 use Drupal\devel\EntityTypeInfo;
28 use Drupal\devel\ToolbarHandler;
29 use Drupal\Core\StringTranslation\TranslatableMarkup;
32 * Implements hook_help().
34 function devel_help($route_name, RouteMatchInterface $route_match) {
35 switch ($route_name) {
36 case 'help.page.devel':
38 $output .= '<h3>' . t('About') . '</h3>';
39 $output .= '<p>' . 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/8/modules/devel']) . '</p>';
40 $output .= '<h3>' . t('Uses') . '</h3>';
42 $output .= '<dt>' . t('Inspecting Service Container') . '</dt>';
43 $output .= '<dd>' . 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>';
44 $output .= '<dt>' . t('Inspecting Routes') . '</dt>';
45 $output .= '<dd>' . 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>';
46 $output .= '<dt>' . t('Inspecting Events') . '</dt>';
47 $output .= '<dd>' . 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>';
51 case 'devel.container_info.service':
52 case 'devel.container_info.parameter':
54 $output .= '<p>' . 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>';
57 case 'devel.route_info':
59 $output .= '<p>' . 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/8/api/routing-system']) . '</p>';
62 case 'devel.event_info':
64 $output .= '<p>' . 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>';
67 case 'devel.reinstall':
68 $output = '<p>' . t('<strong>Warning</strong> - will delete your module tables and configuration.') . '</p>';
69 $output .= '<p>' . 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>';
73 return '<p>' . t('Here are the contents of your <code>$_SESSION</code> variable.') . '</p>';
75 case 'devel.state_system_page':
76 return '<p>' . 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>.', array(':documentation' => "https://www.drupal.org/developing/api/8/state")) . '</p>';
78 case 'devel.layout_info':
80 $output .= '<p>' . 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/8/api/layout-api']) . '</p>';
87 * Implements hook_entity_type_alter().
89 function devel_entity_type_alter(array &$entity_types) {
90 return \Drupal::service('class_resolver')
91 ->getInstanceFromDefinition(EntityTypeInfo::class)
92 ->entityTypeAlter($entity_types);
96 * Implements hook_entity_operation().
98 function devel_entity_operation(EntityInterface $entity) {
99 return \Drupal::service('class_resolver')
100 ->getInstanceFromDefinition(EntityTypeInfo::class)
101 ->entityOperation($entity);
105 * Implements hook_toolbar().
107 function devel_toolbar() {
108 return \Drupal::service('class_resolver')
109 ->getInstanceFromDefinition(ToolbarHandler::class)
114 * Implements hook_menu_links_discovered_alter().
116 function devel_menu_links_discovered_alter(&$links) {
117 // Conditionally add the Layouts info menu link.
118 if (\Drupal::moduleHandler()->moduleExists('layout_discovery')) {
119 $links['devel.layout_info'] = [
120 'title' => new TranslatableMarkup('Layouts Info'),
121 'route_name' => 'devel.layout_info',
122 'description' => new TranslatableMarkup('Overview of layouts available to the site.'),
123 'menu_name' => 'devel',
129 * Implements hook_local_tasks_alter().
131 function devel_local_tasks_alter(&$local_tasks) {
132 if (\Drupal::moduleHandler()->moduleExists('toolbar')) {
133 $local_tasks['devel.toolbar.settings_form'] = [
134 'title' => 'Toolbar Settings',
135 'base_route' => 'devel.admin_settings',
136 'route_name' => 'devel.toolbar.settings_form',
137 'class' => LocalTaskDefault::class,
146 function devel_set_message($msg, $type = NULL) {
147 if (function_exists('drush_log')) {
148 drush_log($msg, $type);
151 drupal_set_message($msg, $type, TRUE);
156 * Gets error handlers.
158 function devel_get_handlers() {
159 $error_handlers = \Drupal::config('devel.settings')->get('error_handlers');
160 if (!empty($error_handlers)) {
161 unset($error_handlers[DEVEL_ERROR_HANDLER_NONE]);
163 return $error_handlers;
167 * Sets a new error handler or restores the prior one.
169 function devel_set_handler($handlers) {
170 if (empty($handlers)) {
171 restore_error_handler();
173 elseif (count($handlers) == 1 && isset($handlers[DEVEL_ERROR_HANDLER_STANDARD])) {
177 set_error_handler('backtrace_error_handler');
182 * Displays backtrace showing the route of calls to the current error.
184 * @param int $error_level
185 * The level of the error raised.
186 * @param string $message
188 * @param string $filename
189 * The filename that the error was raised in.
191 * The line number the error was raised at.
192 * @param array $context
193 * An array that points to the active symbol table at the point the error
196 function backtrace_error_handler($error_level, $message, $filename, $line, $context) {
197 // Hide stack trace and parameters from unqualified users.
198 if (!\Drupal::currentUser()->hasPermission('access devel information')) {
199 // Do what core does in bootstrap.inc and errors.inc.
200 // (We need to duplicate the core code here rather than calling it
201 // to avoid having the backtrace_error_handler() on top of the call stack.)
202 if ($error_level & error_reporting()) {
203 $types = drupal_error_levels();
204 list($severity_msg, $severity_level) = $types[$error_level];
205 $backtrace = debug_backtrace();
206 $caller = Error::getLastCaller($backtrace);
208 // We treat recoverable errors as fatal.
209 _drupal_log_error(array(
210 '%type' => isset($types[$error_level]) ? $severity_msg : 'Unknown error',
211 '@message' => $message,
212 '%function' => $caller['function'],
213 '%file' => $caller['file'],
214 '%line' => $caller['line'],
215 'severity_level' => $severity_level,
216 'backtrace' => $backtrace,
217 ), $error_level == E_RECOVERABLE_ERROR);
223 // Don't respond to the error if it was suppressed with a '@'
224 if (error_reporting() == 0) {
228 // Don't respond to warning caused by ourselves.
229 if (preg_match('#Cannot modify header information - headers already sent by \\([^\\)]*[/\\\\]devel[/\\\\]#', $message)) {
233 if ($error_level & error_reporting()) {
234 // Only write each distinct NOTICE message once, as repeats do not give any
235 // further information and can choke the page output.
236 if ($error_level == E_NOTICE) {
237 static $written = array();
238 if (!empty($written[$line][$filename][$message])) {
241 $written[$line][$filename][$message] = TRUE;
244 $types = drupal_error_levels();
245 list($severity_msg, $severity_level) = $types[$error_level];
247 $backtrace = debug_backtrace();
248 $caller = Error::getLastCaller($backtrace);
250 '%type' => isset($types[$error_level]) ? $severity_msg : 'Unknown error',
251 '@message' => $message,
252 '%function' => $caller['function'],
253 '%file' => $caller['file'],
254 '%line' => $caller['line'],
256 $msg = t('%type: @message in %function (line %line of %file).', $variables);
258 // Show message if error_level is ERROR_REPORTING_DISPLAY_SOME or higher.
259 // (This is Drupal's error_level, which is different from $error_level,
260 // and we purposely ignore the difference between _SOME and _ALL,
262 if (\Drupal::config('system.logging')->get('error_level') != 'hide') {
263 $error_handlers = devel_get_handlers();
264 if (!empty($error_handlers[DEVEL_ERROR_HANDLER_STANDARD])) {
265 drupal_set_message($msg, ($severity_level <= RfcLogLevel::NOTICE ? 'error' : 'warning'), TRUE);
267 if (!empty($error_handlers[DEVEL_ERROR_HANDLER_BACKTRACE_KINT])) {
268 print kpr(ddebug_backtrace(TRUE, 1), TRUE, $msg);
270 if (!empty($error_handlers[DEVEL_ERROR_HANDLER_BACKTRACE_DPM])) {
271 dpm(ddebug_backtrace(TRUE, 1), $msg, 'warning');
275 \Drupal::logger('php')->log($severity_level, $msg);
280 * Implements hook_page_attachments_alter().
282 function devel_page_attachments_alter(&$page) {
283 if (\Drupal::currentUser()->hasPermission('access devel information') && \Drupal::config('devel.settings')->get('page_alter')) {
289 * Wrapper for DevelDumperManager::dump().
291 * Calls the http://www.firephp.org/ fb() function if it is found.
293 * @see \Drupal\devel\DevelDumperManager::dump()
296 $args = func_get_args();
297 \Drupal::service('devel.dumper')->dump($args, NULL, 'firephp');
301 * Wrapper for DevelDumperManager::dump().
303 * Calls dfb() to output a backtrace.
305 * @see \Drupal\devel\DevelDumperManager::dump()
307 function dfbt($label) {
308 \Drupal::service('devel.dumper')->dump(FirePHP::TRACE, $label, 'firephp');
312 * Wrapper for DevelDumperManager::dump().
314 * Wrapper for ChromePHP Class log method.
316 * @see \Drupal\devel\DevelDumperManager::dump()
319 $args = func_get_args();
320 \Drupal::service('devel.dumper')->dump($args, NULL, 'chromephp');
323 if (!function_exists('dd')) {
325 * Wrapper for DevelDumperManager::debug().
327 * @see \Drupal\devel\DevelDumperManager::debug()
329 function dd($data, $label = NULL) {
330 return \Drupal::service('devel.dumper')->debug($data, $label, 'default');
335 * Wrapper for DevelDumperManager::message().
337 * Prints a variable to the 'message' area of the page.
339 * Uses drupal_set_message().
342 * An arbitrary value to output.
343 * @param string $name
344 * Optional name for identifying the output.
345 * @param string $type
346 * Optional message type for drupal_set_message(), defaults to 'status'.
349 * The unaltered input value.
351 * @see \Drupal\devel\DevelDumperManager::message()
353 function dpm($input, $name = NULL, $type = 'status') {
354 \Drupal::service('devel.dumper')->message($input, $name, $type);
359 * Wrapper for DevelDumperManager::message().
361 * Displays a Variable::export() variable to the 'message' area of the page.
363 * Uses drupal_set_message().
366 * An arbitrary value to output.
367 * @param string $name
368 * Optional name for identifying the output.
371 * The unaltered input value.
373 * @see \Drupal\devel\DevelDumperManager::message()
375 function dvm($input, $name = NULL) {
376 \Drupal::service('devel.dumper')->message($input, $name, 'status', 'drupal_variable');
381 * An alias for dpm(), for historic reasons.
383 function dsm($input, $name = NULL) {
384 return dpm($input, $name);
388 * Wrapper for DevelDumperManager::dumpOrExport().
390 * An alias for the devel.dumper service. Saves carpal tunnel syndrome.
392 * @see \Drupal\devel\DevelDumperManager::dumpOrExport()
394 function dpr($input, $export = FALSE, $name = NULL) {
395 return \Drupal::service('devel.dumper')->dumpOrExport($input, $name, $export, 'default');
399 * Wrapper for DevelDumperManager::dumpOrExport().
401 * An alias for devel_dump(). Saves carpal tunnel syndrome.
403 * @see \Drupal\devel\DevelDumperManager::dumpOrExport()
405 function kpr($input, $export = FALSE, $name = NULL) {
406 return \Drupal::service('devel.dumper')->dumpOrExport($input, $name, $export);
410 * Wrapper for DevelDumperManager::dumpOrExport().
412 * Like dpr(), but uses Variable::export() instead.
414 * @see \Drupal\devel\DevelDumperManager::dumpOrExport()
416 function dvr($input, $export = FALSE, $name = NULL) {
417 return \Drupal::service('devel.dumper')->dumpOrExport($input, $name, $export, 'drupal_variable');
421 * Prints the arguments passed into the current function.
423 function dargs($always = TRUE) {
425 if ($always || !$printed) {
426 $bt = debug_backtrace();
427 print kpr($bt[1]['args'], TRUE);
433 * Prints a SQL string from a DBTNG Select object. Includes quoted arguments.
435 * @param object $query
436 * An object that implements the SelectInterface interface.
437 * @param boolean $return
438 * Whether to return the string. Default is FALSE, meaning to print it
439 * and return $query instead.
440 * @param string $name
441 * Optional name for identifying the output.
443 * @return object|string
444 * The $query object, or the query string if $return was TRUE.
446 function dpq($query, $return = FALSE, $name = NULL) {
447 if (\Drupal::currentUser()->hasPermission('access devel information')) {
448 if (method_exists($query, 'preExecute')) {
449 $query->preExecute();
451 $sql = (string) $query;
453 $connection = Database::getConnection();
454 foreach ((array) $query->arguments() as $key => $val) {
455 $quoted[$key] = is_null($val) ? 'NULL' : $connection->quote($val);
457 $sql = strtr($sql, $quoted);
463 return ($return ? NULL : $query);
467 * Prints a renderable array element to the screen using kprint_r().
469 * #pre_render and/or #post_render pass-through callback for kprint_r().
471 * @todo Investigate appending to #suffix.
472 * @todo Investigate label derived from #id, #title, #name, and #theme.
474 function devel_render() {
475 $args = func_get_args();
476 // #pre_render and #post_render pass the rendered $element as last argument.
478 // #pre_render and #post_render expect the first argument to be returned.
483 * Prints the function call stack.
486 * Pass TRUE to return the formatted backtrace rather than displaying it in
487 * the browser via kprint_r().
489 * How many items to pop from the top of the stack; useful when calling from
492 * Options to pass on to PHP's debug_backtrace().
494 * @return string|NULL
495 * The formatted backtrace, if requested, or NULL.
497 * @see http://php.net/manual/en/function.debug-backtrace.php
499 function ddebug_backtrace($return = FALSE, $pop = 0, $options = DEBUG_BACKTRACE_PROVIDE_OBJECT) {
500 if (\Drupal::currentUser()->hasPermission('access devel information')) {
501 $backtrace = debug_backtrace($options);
503 array_shift($backtrace);
505 $counter = count($backtrace);
506 $path = $backtrace[$counter - 1]['file'];
507 $path = substr($path, 0, strlen($path) - 10);
508 $paths[$path] = strlen($path) + 1;
509 $paths[DRUPAL_ROOT] = strlen(DRUPAL_ROOT) + 1;
512 // Show message if error_level is ERROR_REPORTING_DISPLAY_SOME or higher.
513 // (This is Drupal's error_level, which is different from $error_level,
514 // and we purposely ignore the difference between _SOME and _ALL,
516 if (\Drupal::config('system.logging')->get('error_level') != 'hide') {
517 while (!empty($backtrace)) {
519 if (isset($backtrace[0]['file'])) {
520 $call['file'] = $backtrace[0]['file'];
521 foreach ($paths as $path => $len) {
522 if (strpos($backtrace[0]['file'], $path) === 0) {
523 $call['file'] = substr($backtrace[0]['file'], $len);
526 $call['file'] .= ':' . $backtrace[0]['line'];
528 if (isset($backtrace[1])) {
529 if (isset($backtrace[1]['class'])) {
530 $function = $backtrace[1]['class'] . $backtrace[1]['type'] . $backtrace[1]['function'] . '()';
533 $function = $backtrace[1]['function'] . '()';
535 $backtrace[1] += array('args' => array());
536 foreach ($backtrace[1]['args'] as $key => $value) {
537 $call['args'][$key] = $value;
541 $function = 'main()';
542 $call['args'] = $_GET;
544 $nicetrace[($counter <= 10 ? $nbsp : '') . --$counter . ': ' . $function] = $call;
545 array_shift($backtrace);
556 * Implements hook_form_FORM_ID_alter().
558 * Adds mouse-over hints on the Permissions page to display
559 * language-independent machine names and module base names.
561 * @see \Drupal\user\Form\UserPermissionsForm::buildForm()
563 function devel_form_user_admin_permissions_alter(&$form, FormStateInterface $form_state) {
564 if (\Drupal::currentUser()->hasPermission('access devel information') && \Drupal::config('devel.settings')->get('raw_names')) {
565 foreach (Element::children($form['permissions']) as $key) {
566 if (isset($form['permissions'][$key][0])) {
567 $form['permissions'][$key][0]['#wrapper_attributes']['title'] = $key;
569 elseif(isset($form['permissions'][$key]['description'])) {
570 $form['permissions'][$key]['description']['#wrapper_attributes']['title'] = $key;
577 * Implements hook_form_FORM_ID_alter().
579 * Adds mouse-over hints on the Modules page to display module base names.
581 * @see \Drupal\system\Form\ModulesListForm::buildForm()
582 * @see theme_system_modules_details()
584 function devel_form_system_modules_alter(&$form, FormStateInterface $form_state) {
585 if (\Drupal::currentUser()->hasPermission('access devel information') && \Drupal::config('devel.settings')->get('raw_names', FALSE) && isset($form['modules']) && is_array($form['modules'])) {
586 foreach (Element::children($form['modules']) as $group) {
587 if (is_array($form['modules'][$group])) {
588 foreach (Element::children($form['modules'][$group]) as $key) {
589 if (isset($form['modules'][$group][$key]['name']['#markup'])) {
590 $form['modules'][$group][$key]['name']['#markup'] = '<span title="' . $key . '">' . $form['modules'][$group][$key]['name']['#markup'] . '</span>';
599 * Implements hook_query_TAG_alter().
601 * Makes debugging entity query much easier.
605 * $query = \Drupal::entityQuery('node');
606 * $query->condition('status', NODE_PUBLISHED);
607 * $query->addTag('debug');
611 function devel_query_debug_alter(AlterableInterface $query) {
612 if (!$query->hasTag('debug-semaphore')) {
613 $query->addTag('debug-semaphore');