Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 4 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -115,7 +115,7 @@ render based on the main query, and renders it.
Profile key metrics for WordPress hooks (actions and filters).

~~~
wp profile hook [<hook>] [--all] [--spotlight] [--url=<url>] [--fields=<fields>] [--format=<format>] [--order=<order>] [--orderby=<fields>] [--search=<pattern>]
wp profile hook [<hook>] [--all] [--spotlight] [--url=<url>] [--fields=<fields>] [--format=<format>] [--order=<order>] [--orderby=<fields>] [--search=<pattern>] [--plugin]
~~~

In order to profile callbacks on a specific hook, the action or filter
Expand Down Expand Up @@ -164,6 +164,9 @@ will need to execute during the course of the request.
[--search=<pattern>]
Filter callbacks to those matching the given search pattern (case-insensitive).

[--plugin]
Group callback metrics by plugin. Must-use plugins are listed with a `mu-plugins/` prefix. Callbacks that don't belong to a plugin or must-use plugin are left out. Requires --all or a specific hook.

**EXAMPLES**

# Profile a hook.
Expand Down
1 change: 1 addition & 0 deletions composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
"wp-cli/wp-cli": "^3.0"
},
"require-dev": {
"wp-cli/extension-command": "^3",
"wp-cli/wp-cli-tests": "^5"
},
"config": {
Expand Down
64 changes: 64 additions & 0 deletions features/profile-hook.feature
Original file line number Diff line number Diff line change
Expand Up @@ -152,6 +152,70 @@ Feature: Profile a specific hook
"""
And STDERR should be empty

Scenario: Group callback metrics by plugin
Given a WP install
And a wp-content/plugins/resource-test/resource-test.php file:
"""
<?php
/**
* Plugin Name: Resource Test
*/
function resource_test_init_callback() {
wp_cache_get( 'resource_test' );
}
add_action( 'init', 'resource_test_init_callback' );
"""
And a wp-content/plugins/resource-test/functions.php file:
"""
<?php
// Never loaded, only shares its relative path with the theme's functions.php.
"""
And a wp-content/mu-plugins/resource-test.php file:
"""
<?php
add_action( 'init', function () {
wp_cache_get( 'mu_resource_test_1' );
wp_cache_get( 'mu_resource_test_2' );
} );
"""
And a wp-content/themes/resource-test/style.css file:
"""
/*
Theme Name: Resource Test Theme
*/
"""
And a wp-content/themes/resource-test/index.php file:
"""
<?php
"""
And a wp-content/themes/resource-test/functions.php file:
"""
<?php
add_action( 'init', function () {
wp_cache_get( 'theme_resource_test_1' );
wp_cache_get( 'theme_resource_test_2' );
wp_cache_get( 'theme_resource_test_3' );
wp_cache_get( 'theme_resource_test_4' );
} );
"""
And I run `wp plugin activate resource-test`
Comment thread
swissspidy marked this conversation as resolved.
Resolved
And I run `wp theme activate resource-test`

When I run `wp profile hook init --plugin --fields=plugin,cache_hits,cache_misses --orderby=plugin`
Then STDOUT should be a table containing rows:
| plugin | cache_hits | cache_misses |
| mu-plugins/resource-test | 0 | 2 |
| resource-test | 0 | 1 |
| total (2) | 0 | 3 |
And STDERR should be empty

When I try `wp profile hook --plugin`
Then STDERR should be:
"""
Error: --plugin requires --all or a specific hook.
"""
And the return code should be 1

Scenario: Hooks should only be called once
Given a WP install
And a wp-content/mu-plugins/action-test.php file:
Expand Down
2 changes: 1 addition & 1 deletion features/profile.feature
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ Feature: Basic profile usage
"""
usage: wp profile eval <php-code> [--hook[=<hook>]] [--fields=<fields>] [--format=<format>] [--order=<order>] [--orderby=<fields>]
or: wp profile eval-file <file> [--hook[=<hook>]] [--fields=<fields>] [--format=<format>] [--order=<order>] [--orderby=<fields>]
or: wp profile hook [<hook>] [--all] [--spotlight] [--url=<url>] [--fields=<fields>] [--format=<format>] [--order=<order>] [--orderby=<fields>] [--search=<pattern>]
or: wp profile hook [<hook>] [--all] [--spotlight] [--url=<url>] [--fields=<fields>] [--format=<format>] [--order=<order>] [--orderby=<fields>] [--search=<pattern>] [--plugin]
or: wp profile queries [--url=<url>] [--hook=<hook>] [--callback=<callback>] [--time_threshold=<seconds>] [--fields=<fields>] [--format=<format>] [--order=<order>] [--orderby=<fields>]
or: wp profile stage [<stage>] [--all] [--spotlight] [--url=<url>] [--fields=<fields>] [--format=<format>] [--order=<order>] [--orderby=<fields>]

Expand Down
60 changes: 57 additions & 3 deletions src/Command.php
Original file line number Diff line number Diff line change
Expand Up @@ -244,6 +244,9 @@ public function stage( $args, $assoc_args ) {
* [--search=<pattern>]
* : Filter callbacks to those matching the given search pattern (case-insensitive).
*
* [--plugin]
* : Group callback metrics by plugin. Must-use plugins are listed with a `mu-plugins/` prefix. Callbacks that don't belong to a plugin or must-use plugin are left out. Requires --all or a specific hook.
*
* ## EXAMPLES
*
* # Profile a hook.
Expand All @@ -266,18 +269,23 @@ public function stage( $args, $assoc_args ) {
* @when before_wp_load
*
* @param array{0?: string} $args Positional arguments.
* @param array{all?: bool, spotlight?: bool, url?: string, fields?: string, format: string, order: string, orderby?: string} $assoc_args
* @param array{all?: bool, spotlight?: bool, plugin?: bool, search?: string, url?: string, fields?: string, format: string, order: string, orderby?: string} $assoc_args
* @return void
*/
public function hook( $args, $assoc_args ) {

$focus = Utils\get_flag_value( $assoc_args, 'all', isset( $args[0] ) ? $args[0] : null );
$focus = Utils\get_flag_value( $assoc_args, 'all', isset( $args[0] ) ? $args[0] : null );
$plugin = Utils\get_flag_value( $assoc_args, 'plugin', false );

$order_val = Utils\get_flag_value( $assoc_args, 'order', 'ASC' );
$order = is_string( $order_val ) ? $order_val : 'ASC';
$orderby_val = Utils\get_flag_value( $assoc_args, 'orderby', null );
$orderby = ( is_string( $orderby_val ) || is_null( $orderby_val ) ) ? $orderby_val : null;

if ( $plugin && ! $focus ) {
WP_CLI::error( '--plugin requires --all or a specific hook.' );
}

$profiler = new Profiler( 'hook', $focus );
$profiler->run();

Expand All @@ -288,7 +296,9 @@ public function hook( $args, $assoc_args ) {
remove_all_actions( 'shutdown' );
}

if ( $focus ) {
if ( $focus && $plugin ) {
$base = array( 'plugin' );
} elseif ( $focus ) {
$base = array( 'callback', 'location' );
} else {
$base = array( 'hook', 'callback_count' );
Expand Down Expand Up @@ -319,6 +329,9 @@ public function hook( $args, $assoc_args ) {
}
$loggers = self::filter_by_callback( $loggers, $search );
}
if ( $plugin ) {
$loggers = self::group_by_plugin( $loggers );
}
$formatter->display_items( $loggers, true, $order, $orderby );
}

Expand Down Expand Up @@ -792,4 +805,45 @@ function ( $logger ) use ( $pattern ) {
}
);
}

/**
* Group callback loggers by plugin.
*
* @param array<\WP_CLI\Profile\Logger> $loggers
* @return array<\WP_CLI\Profile\Logger>
*/
private static function group_by_plugin( $loggers ) {
$plugins = array();

foreach ( $loggers as $logger ) {
if ( ! isset( $logger->plugin ) ) {
continue;
}
$plugin = (string) $logger->plugin;
if ( ! isset( $plugins[ $plugin ] ) ) {
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
$plugins[ $plugin ] = new Logger(
array(
'plugin' => $plugin,
)
);
}

$plugins[ $plugin ]->time += $logger->time;
$plugins[ $plugin ]->query_time += $logger->query_time;
$plugins[ $plugin ]->query_count += $logger->query_count;
$plugins[ $plugin ]->cache_hits += $logger->cache_hits;
$plugins[ $plugin ]->cache_misses += $logger->cache_misses;
$plugins[ $plugin ]->request_time += $logger->request_time;
$plugins[ $plugin ]->request_count += $logger->request_count;
}

foreach ( $plugins as $plugin_logger ) {
$total_cache = $plugin_logger->cache_hits + $plugin_logger->cache_misses;
if ( $total_cache ) {
$plugin_logger->cache_ratio = round( ( $plugin_logger->cache_hits / $total_cache ) * 100, 2 ) . '%';
}
}

return array_values( $plugins );
}
}
1 change: 1 addition & 0 deletions src/Logger.php
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
* @property string $callback
* @property string $location
* @property string $hook
* @property string $plugin
*/
class Logger {

Expand Down
51 changes: 51 additions & 0 deletions src/Profiler.php
Original file line number Diff line number Diff line change
Expand Up @@ -100,6 +100,13 @@ public function get_loggers() {
$logger->callback = $name;
$logger->location = $location;
}
if ( ! isset( $logger->plugin ) ) {
// Determine plugin ownership from the full path, before it gets shortened.
$plugin = self::get_plugin_from_location( $logger->location );
if ( null !== $plugin ) {
$logger->plugin = $plugin;
}
}
$logger->location = self::get_short_location( $logger->location );
$this->loggers[ $i ] = $logger;
}
Expand Down Expand Up @@ -650,6 +657,50 @@ private static function get_name_location_from_callback( $callback ) {
return array( $name, $location );
}

/**
* Get the plugin or must-use plugin a full callback location belongs to.
*
* Regular plugins are identified by their slug (e.g. `akismet`), must-use
* plugins by their slug prefixed with `mu-plugins/` (e.g. `mu-plugins/example`),
* so that a regular and a must-use plugin with the same slug stay separate.
*
* @param string $location Full location, e.g. `/path/to/wp-content/plugins/akismet/akismet.php:12`.
* @return string|null Null if the location doesn't belong to a plugin.
*/
private static function get_plugin_from_location( $location ) {
$file = (string) preg_replace( '/:\d+$/', '', Path::normalize( $location ) );
if ( '' === $file ) {
return null;
}

$dirs = array();
if ( defined( 'WPMU_PLUGIN_DIR' ) ) {
$dirs['mu-plugins/'] = WPMU_PLUGIN_DIR;
}
if ( defined( 'WP_PLUGIN_DIR' ) ) {
$dirs[''] = WP_PLUGIN_DIR;
}

foreach ( $dirs as $prefix => $dir ) {
$candidates = array( Path::normalize( $dir ) );
$real_dir = realpath( $dir );
if ( false !== $real_dir ) {
$candidates[] = Path::normalize( $real_dir );
}
foreach ( array_unique( $candidates ) as $candidate ) {
$candidate = rtrim( $candidate, '/' ) . '/';
if ( 0 !== stripos( $file, $candidate ) ) {
continue;
}
$segments = explode( '/', substr( $file, strlen( $candidate ) ) );
$slug = count( $segments ) > 1 ? $segments[0] : basename( $segments[0], '.php' );
return '' === $slug ? null : $prefix . $slug;
}
}

return null;
}

/**
* Get the short location from the full location
*
Expand Down