Keep track of filter depth to appropriately handle recursion

This commit is contained in:
Daniel Bachhuber 2016-10-07 15:27:29 -07:00
parent 5a3cffcd79
commit 5d4d6450ce
2 changed files with 10 additions and 3 deletions

View file

@ -45,6 +45,7 @@ Feature: Profile a specific hook
| runcommand_shutdown_hook() | 0 | 1 |
| wp_ob_end_flush_all() | 0 | 0 |
| total | 0 | 1 |
And STDERR should be empty
Scenario: Indicate where a callback is defined with profiling a hook
Given a WP install
@ -63,6 +64,7 @@ Feature: Profile a specific hook
| callback | location | cache_hits | cache_misses |
| runcommand_custom_action_hook() | mu-plugins/custom-action.php:2 | 0 | 1 |
| total | | 0 | 1 |
And STDERR should be empty
Scenario: Hooks should only be called once
Given a WP install

View file

@ -13,6 +13,7 @@ class Command {
private $focus_hook = null;
private $previous_filter = null;
private $previous_filter_callbacks = null;
private $filter_depth = 0;
private $focus_query_offset = 0;
private static $exception_message = "Need to bail, because can't restore the hooks";
@ -273,7 +274,7 @@ class Command {
$this->loggers[ $current_filter ]->start();
}
if ( ! is_null( $this->previous_filter_callbacks ) ) {
if ( ! is_null( $this->previous_filter_callbacks ) && 0 === $this->filter_depth ) {
if ( is_a( $wp_filter[ $this->previous_filter ], 'WP_Hook' ) ) {
$wp_filter[ $this->previous_filter ]->callbacks = $this->previous_filter_callbacks;
} else {
@ -282,8 +283,9 @@ class Command {
$this->previous_filter_callbacks = null;
}
if ( $this->focus_hook && $current_filter === $this->focus_hook ) {
if ( $this->focus_hook && $current_filter === $this->focus_hook && 0 === $this->filter_depth ) {
$this->wrap_current_filter_callbacks( $current_filter );
$this->filter_depth = 1;
}
WP_CLI::add_wp_hook( $current_filter, array( $this, 'wp_hook_end' ), 9999 );
@ -294,7 +296,6 @@ class Command {
*/
private function wrap_current_filter_callbacks( $current_filter ) {
global $wp_filter;
$this->previous_filter_callbacks = null;
if ( ! isset( $wp_filter[ $current_filter ] ) ) {
return;
@ -350,6 +351,10 @@ class Command {
$logger->stop_hook_timer();
}
if ( $this->focus_hook && $current_filter === $this->focus_hook ) {
$this->filter_depth = 0;
}
$current_filter = current_filter();
if ( in_array( $current_filter, $this->stage_hooks ) ) {
$this->loggers[ $current_filter ]->stop();