pfaciana/wp-debug-bar

这是一个为WordPress添加调试菜单到管理栏的调试栏,显示查询、缓存和其他有用的调试信息。

1.2.5 2023-03-23 08:35 UTC

This package is auto-updated.

Last update: 2024-09-23 12:03:53 UTC


README

一个受到wordpressdotorg的Debug Bar启发(且与之兼容)的WordPress调试栏,结合了我对可用性和功能的个人观点

此仓库旨在与现有调试栏插件协同工作并支持它们。

入门

将作为composer包安装到与您的插件文件相同的目录中,并在插件头部注释中添加 header comments

composer require pfaciana/wp-debug-bar

如果您尚未使用其他composer包,那么请在插件头部注释之后添加autoload.php。

/**
 * Plugin Name: YOUR PLUGIN NAME
 */
 
require __DIR__ . '/vendor/autoload.php';

您可以在所有插件中安装WP Debug Bar,但只有第一个实例会加载。其余的将被忽略。

与wordpressdotorg的原始Debug Bar相比,这个版本有几个不同之处,比如可以快速禁用面板而不必禁用整个插件。您只需点击面板名称旁边的切换图标,该代码就不会在下次页面加载时运行。这对于某些资源密集型的面板非常有用,您可能不希望在调试顽固问题时不断启用和禁用插件。

此项目还允许轻松更改可以查看面板的用户角色。有时(在预发布环境中)您可能只想调试访客可以看到的内容。您可以在设置面板中暂时更改此设置。默认情况下,面板可以决定面板可见所需的最小权限。这通常是因为面板可能会显示敏感数据,这些数据不应由访客或权限较低的用户访问。如果没有面板显式设置,则面板默认为edit_posts。但是,如果您绝对确信您想在受控环境中公开这些数据,则可以使用debug_bar_panel_capability过滤器来覆盖此设置,如下所示...

// This example will allow visibility to ALL Panels to ALL site visitors,
// excepts Panels titled `Environment` or `Globals`
// $panel is the Panel class object
add_filter( 'debug_bar_panel_capability', function ( string $capability, string $title, Panel $panel ) {
    if ( !in_array( $title, [ 'Environment', 'Globals' ] ) ) {
        return ''; // Setting a $capability to '', '*', 'any' or 'all' shows to panel to all site visitors
    }

    return $capability;
}, 10, 3 );

有关WP Debug附带的所有面板的完整列表,请参阅本文档的底部

以下几节将详细介绍可以与特定调试面板交互的用户定义代码

Kint Debugger & Console Class

WP Debug Bar包含一个自定义的Kint Debugger面板,用于输出Kint Debugger的结果

注意:Kint面板和Kint Debugger都包含在本安装中

虽然以下对Kint的默认使用仍然有效...

// Properties
Kint::$expanded = true;
Kint::$enabled_mode = FALSE;
Kint::$max_depth = 3;

// Methods
Kint::dump($_SERVER); // Dump any number of variables
Kint::trace(); // Dump a backtrace

// Shorthand
d($_SERVER); // d() is a shortcut for Kint::dump()
t(); // t() is a shortcut for Kint::trace()

...但是建议使用WP Debug Bar创建的新console实例(而不是Kint实例)来进行方法调用,因为有一些增强功能可以改善用户体验。

WP Debug Bar console

consoleKint方法dumptrace的替代品,以及一些旨在与浏览器中的console 类似的方法。因此Kint::dump()变为console::log()Kint::trace()变为console::trace()。如果您熟悉console.log()console.assert()等,它们将以类似的方式工作。除了将内容显示到Kint面板外,这些方法还返回相关数据以用于您的代码。以下是可以用的其他方法...

// `console::log` is same as `Kint::dump`, accepts unlimited arguments and dumps them to the Panel
// Each call to log groups all the arguments together in one section
// Returns the value of the first argument passed

console::log( ...$args ) : mixed

// `console::trace` is same as `Kint::trace`, accept the same signature as php's debug_backtrace
// If $options is true, then response is debug_backtrace() with the default arguments
// If $options and/or $limit is defined, then the response is debug_backtrace($options, $limit)
// Returns the backtrace array, or NULL if no arguments are defined
// Alias: console::backtrace()
console::trace( true|int $options = NULL, int $limit = 0 ) : null|array

以下所有方法都接受额外的变量作为$context参数,以附加到组的底部以提供额外上下文。$context参数是可选的。

日志级别

类似于PSR-3: Logger Interface

// These methods work the same as `console::log` except they add a relevant icon and header text with the level
// Returns the $message prefixed with the message level
console::emergency( string $message, ...$context ) : string  // Header flashes red quickly
console::critical( string $message, ...$context ) : string  // Header flashes red 
console::alert( string $message, ...$context ) : string  // Header flashes red slowly
console::error( string $message, ...$context ) : string  // Header is red
console::warn( string $message, ...$context ) : string  // Header is orange
console::notice( string $message, ...$context ) : string  // Header is yellow
console::debug( string $message, ...$context ) : string  // Header is green
console::info( string $message, ...$context ) : string // Header is white

// Usage
console.warn("This is a Warning!")
// Outputs
// `⚠ Warning: This is a Warning!` (in orange color)

测试条件

// Checks a condition and displays pass or fail to the panel
// $message is an optional text to display after pass/fail header
// Returns the result of the $condition
console::test( bool $condition, string $message, ...$context ) : bool

// Checks a condition and displays it to the panel ONLY if it fails
// $error_message is an optional text to display after fail header
// Returns the result of the $condition
console::assert( bool $condition, string $error_message, ...$context ) : bool

// Usage
console::test( $large_number > $small_number, 'Checking to make sure large > small', $large_number, $small_number);
console::assert( $large_number > $small_number, 'Large is not greater than small', $large_number, $small_number);

计时器

您可以通过定义$label来管理多个计时器。否则,默认情况下所有计时器方法应用于同一组。

// Start a Timer
// $label is the name of the timer group, defaults to 'default'
// Alias: console::timeStart()
console::time( string $label = 'default', ...$context ) : float

// Display the current duration of a Timer
// $label is the name of the timer group, defaults to 'default'
// Returns the number of seconds the timer has been running
console::timeLog( string $label = 'default', ...$context ) : float

// Stop a Timer
// $label is the name of the timer group, defaults to 'default'
// Returns the duration of the timer, in seconds
console::timeEnd( string $label = 'default', ...$context ) : float

// Usage
console::time();
// some code to time
console::timeEnd();

计数器

您可以通过定义$label来管理多个计数器。否则,默认情况下所有计时器方法应用于同一组。

// Start a Counter
// $label is the name of the counter group, defaults to 'default'
// Return the number of times the counter group has been called
console::count( string $label = 'default', ...$context ) : int

// Reset a Counter to zero
// $label is the name of the counter group, defaults to 'default'
console::countReset( string $label = 'default', ...$context ) : int

// Usage
console::count(); // do something...
console::count(); // do something...
console::countReset();  // start over...
console::count(); // do something...

内存检查

// Display and return the current memory being used (in MB)
console::memory( ...$context ) : float
// Display and return the peak memory usage (in MB)
console::memoryPeak( ...$context ) : float
// Display and return (as an array) both the current memory used the peak memory usage (in MB)
console::memoryBoth( ...$context ) : float[]
// Reset the peak memory usage, if `memory_reset_peak_usage` function exists in php
console::memoryReset( ...$context ) : float

WordPress 钩子

虽然不建议在生产环境中使用此类调试工具,但您可能希望在开发、测试或预发布环境中使用。为此,可能会担心意外将带有 console 的代码推送到未安装 WP Debug Bar 的不同环境中。如果是这种情况,则缺失的 console 将引发错误。因此,如果您对此表示担忧,则可以使用 WordPress 钩子将输出到 Kint 面板。在这种情况下,即使该代码被错误地推送,钩子也将简单地什么都不做,避免 PHP 错误。钩子名称接受类和方法的双冒号(::)和点(.)连接。因此,console::logconsole.log 都可以作为动作名称工作。我发现点符号更容易更快地输入,所以我添加了这个额外的选项。

// Usage
do_action( 'console.log', $a, $b, $c );
do_action_ref_array( 'console::log', [ &$a, $b, $c ] );
$error = apply_filters( 'console::error', 'This is an ERROR' )

WP Debug Bar 还发布了针对特定 console 事件的动作,这可能对通知第三方工具很有用。

# Level Logging (converts string level to RFC 5424 and Monolog integer versions as well) 
do_action( 'console/level', string $level, string $message, mixed[] $context );
do_action( 'console/level/rfc5424', int $rfc5424, string $message, mixed[] $context );
do_action( 'console/level/monolog', int $monolog, string $message, mixed[] $context );
do_action( "console/level/{$level}", string $message, mixed[] $context );
do_action( "console/level/rfc5424/{$rfc5424}", string $message, mixed[] $context );
do_action( "console/level/monolog/{$monolog}", string $message, mixed[] $context );

# Conditions
do_action( 'console/test', bool $condition, string $message, mixed[] $context );
do_action( 'console/assert', bool $condition, string $message, mixed[] $context );
do_action( 'console/condition', 'test'|'assert' $type, bool $condition, string $message, mixed[] $context );

# Timers (after a Timer has ended)
do_action( 'console/time', string $label, float $duration, mixed[] $context );
do_action( "console/time/{$label}", float $duration, mixed[] $context );

// Usage
add_action( 'console/level/monolog', function ( int $level, string $message, array $context ) {
    if( $level >= 400 ) {
        // The last item in the $context array is the $level's string name 
        $level_name = (string) array_pop( $context );
        notify_developer("There was a(n) {$level_name}");
    }
}, 10, 3 );

add_action( 'console/level/rfc5424', function ( int $level, string $message, array $context ) {
    if( $level === 7 ) {
        write_to_debug_log($message, $context);
    }
    
    if( $level >= 4 && $level <= 5 ) {
        notify_team_lead($message, $context);
    }
}, 10, 3 );

add_action( 'console/condition', function ( string $type, bool $condition, string $message,  array $context ) {
    if( $type === 'assert' && !$condition ) {
        notify_current_user($message, $context);
    }
}, 10, 4 );

跟踪代码段中触发的钩子

有时您可能想知道与它们的输入和输出一起触发的钩子。例如,有第三方代码将某些内容输出到缓冲区,您想修改该文本。第三方文档可能不足,如果有很多嵌套代码,尝试设置断点进行调试可能需要很长时间。理想的情况是找出在函数调用上运行了哪些过滤器,看看您是否可以通过插件或主题中的钩子来修改它。这就是钩子跟踪发挥作用的地方。当设置监视器时,它会在 WP Debug Bar 的钩子面板上显示。

如何使用

// In some third party code you might see...
echo some_function();

// You change that to...
do_action( 'debugbar/watch', (string) $label );
echo some_function();
do_action( 'debugbar/unwatch', (string) $label );
// NOTE: $label is the tracker label and used to identify and filter rows in the Panel UI.
// $label is arbitrary and should be a string.

执行此操作后,钩子面板将显示一个新的跟踪部分。它将只显示在 debugbar/watchdebugbar/unwatch 动作之间触发的钩子。现在您可以看到是否存在相关的过滤器,并可以将其挂钩以修改输出。

替代用途

这些功能相同,但可能是一个更好的替代方案。

// Alternate Option #1
$unwatch = apply_filters( 'debugbar/watch', 'Some Watcher Name' );
echo do_something();
$unwatch();

// Alternate Option #2
do_action( 'debugbar/watch', 'Do Something', function() {
    echo do_something();
});

多个跟踪器

do_action( 'debugbar/watch', 'watcher #1' );
echo some_function();
do_action( 'debugbar/watch', 'watcher #2' );
echo some_other_function();
do_action( 'debugbar/unwatch', 'watcher #1' );
do_action( 'debugbar/unwatch', 'watcher #2' );

跟踪器筛选

有时跟踪器表中可能会显示数十或数百个筛选器。因此,您也可以通过使用 debugbar/watch/filter 筛选器来缩小此列表。

// In this example, we'll only show tracker hooks where the filter's return value is a non-empty string
// $show is the boolean value to show or hide the row for that specific tracker
// $hook is the array of data for that specific tracker
add_filter( 'debugbar/watch/filter', function ( bool $show, array $hook ) {
    if ( !empty( $hook['value'] ) && $hook['value']['type'] === 'string' ) {
        return $show;
    }
    return FALSE;
}, 10, 2 );

// Here is an example of a $hook variable passed as the second argument
// This matches what you see in the Hooks Panel table
$hook = [
    // Array of tracker names watching this hook
    'trackers' => ['watcher #1', 'watcher #2'],
    
    // Hook Type
    'type'     => 'filter', // or action
    
    // Name of the Hook
    'name'     => 'hook/name/called',
    
    // This is the value returned after the filter is complete (the Output column in the UI)
    'value'    => [ // An $arg array
          'text' => NULL, // A representation of the return value (what you see in the Hook Table)
          'type' => 'null', // The variable type of the returned value
    ],
    
    // This is the initial value of the variable to be filtered
    'input'    => [ // An $arg array
        'type' => 'same', // the filtered value did not change as a result of the filter
    ],
    
    // This is additional context sent to the variable to be filtered (argument 2+ in the hook)
    'args'     => [ // An array of $arg arrays
        [
            'text' => 'some text',
            'type' => 'string',
        ],
        [
            'text' => FALSE,
            'type' => 'boolean',
        ],
    ],
    
    // How many milliseconds it took to complete the code being tracked  
    'duration' => 0.15,
    
    // How many millisecond since the script was started
    'time'     => 191.01,
    
    // Name of the parent Hook (if applicable)
    'parent'   => 'parent/hook/name',
    
    // An array of $file arrays
    'subscribers' => [
        [
            'text'     => 'Plugin: Some Plugin > includes.php:218 [10] x2',
            'priority' => 10,
            'count'    => 2,
        ],
    ],
    
    // An array of $file arrays
    'publishers'  => [ 
        [
            'text' => 'Plugin: Some Other Plugin > includes/helpers.php:2474',
        ],
    ],
]

常规

此功能还包括我的另一个项目,名为 WP Routines。您可以在其文档中查看该项目以获取更多信息。WP Routines 是一个独立的项目,无需 WP Debug Bar 即可运行,但 WP Debug Bar 扩展了其功能,以与调试条面板一起使用。

内置面板

环境

  • 服务器详细信息
    • PHP 和 WordPress 规格(最重要的项目)
    • PHP INI 配置(最重要的项目)
    • 数据库规格
    • Web 服务器规格
  • WordPress 常量
    • 列出在 WordPress 中定义的最重要常量及其默认值的观点
  • PHP 扩展
    • 可用的活动扩展
  • 错误报告
    • 基于 php.ini 中的 error_reporting

全局变量

  • 用户常量
    • 所有定义的常量
  • WordPress 全局变量
    • 所有全局变量
  • WordPress 条件
    • 描述当前请求或当前WordPress实例类型的布尔条件函数
  • 类常量和静态变量
    • 类内部定义的所有常量和静态变量
  • PHP常量
    • PHP本身定义的所有常量

模板化

  • 当前主题信息
  • 当前页面的当前模板文件
  • 当前页面的模板文件层次结构
  • 当前页面的body标签上的CSS类
  • 可用的简码
  • 已注册的主题功能
    • 已启用和已禁用的功能

  • 包含上下文信息的当前页面上的Gutenberg块
  • 此WordPress安装中的所有Gutenberg块及其上下文信息
  • 块分类
  • 此WordPress安装中的块模式
  • 块模式分类

文章类型

  • 文章类型
  • 分类法
  • 与文章类型配对的分类法
  • 文章状态
  • 图片尺寸

用户角色和权限

  • 用户角色
  • 权限

样式和脚本

  • 已注册的样式
  • 已注册的脚本

重写规则

  • 活动页面查询
    • 匹配的URL查询
    • 查询变量
    • 页面上的请求(GET/POST)查询
  • 所有已注册的重写规则
  • 所有已注册的重写标签

SQL查询

  • 当前页面上运行的SQL查询

WordPress 钩子

  • 所有钩子(在plugins_loaded之后)
    • 可选的,用户定义的钩子调试

Kint调试器

WP例程

  • 用户定义的代码,将实时输出流到Debug Bar面板

特别感谢

感谢 TabulatorKint,任何提供灵感的开源软件,当然还有 WordPress