Skip to content

Instantly share code, notes, and snippets.

@grayside
Created August 11, 2012 19:01
Show Gist options
  • Save grayside/3326438 to your computer and use it in GitHub Desktop.
Save grayside/3326438 to your computer and use it in GitHub Desktop.
Menu Trace
#!/usr/bin/env drush
<?php
/**
* Menu Trace
*
* Drush snippet that traces the Drupal modules that define and modify a given menu
* route.
*
* @see menu_router_build(), drupal_alter().
*/
$key = drush_shift();
if (empty($key)) {
return drush_set_error('MENUTRACE_NO_PATH', 'Menu Trace needs a valid menu route.');
}
$key = preg_replace(
array('/^node\/\d+/', '/^user\/(\d+|%user)\/edit/', '/^user\/(\d+|%user)$/'),
array('node/%node', 'user/%user_category/edit', 'user/%user_uid_optional'),
$key
);
drush_print(dt('Searching for menu info for route "!route"...', array('!route' => $key)));
$results = $pipe = array();
// Mock hook_menu() to find the original definition of our route.
$callbacks = array();
foreach (module_implements('menu') as $module) {
$router_items = call_user_func($module . '_menu');
if (array_key_exists($key, $router_items)) {
$results[$module] = json_encode($router_items[$key]);
}
// Even though we found what we want, need the full menu routes to avoid
// errors when we pass through the hook_menu_alter() test.
if (isset($router_items) && is_array($router_items)) {
foreach (array_keys($router_items) as $path) {
$router_items[$path]['module'] = $module;
}
$callbacks = array_merge($callbacks, $router_items);
}
}
// Identify and record each hook_menu_alter() implementation that changes the
// menu route definition.
$running = reset($results);
foreach (module_implements('menu_alter') as $module) {
$function = $module . '_menu_alter';
$function($callbacks);
$current = json_encode($callbacks[$key]);
if ($running != $current) {
$running = $current;
if (isset($results[$module])) {
$module = $module . ' (again!)';
}
$results[$module] = $current;
}
}
// Output the results.
if (!drush_get_context('DRUSH_PIPE')) {
if (drush_get_context('DRUSH_VERBOSE')) {
foreach ($results as &$item) {
$item = json_decode($item, TRUE);
}
}
drush_print_r($results);
}
else {
drush_print_pipe(array_keys($results));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment