From a678997c44b83cc60afb79b403711bd15a28312e Mon Sep 17 00:00:00 2001 From: Andrey Savchenko Date: Tue, 29 Jan 2019 16:23:49 +0200 Subject: [PATCH] Fixed handling of reoccurring hook events. --- CHANGELOG.md | 3 +++ src/Record/Collector/Hook_Collector.php | 30 +++++++++++++++++++++++++ 2 files changed, 33 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 1531138..02063b5 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,9 @@ and this project adheres to [Semantic Versioning](http://semver.org/). ## Unreleased +### Fixed +- handling of reoccurring hook events + ## 3.1 - 2019-01-22 ### Added diff --git a/src/Record/Collector/Hook_Collector.php b/src/Record/Collector/Hook_Collector.php index 3cd1456..791b585 100644 --- a/src/Record/Collector/Hook_Collector.php +++ b/src/Record/Collector/Hook_Collector.php @@ -26,6 +26,9 @@ class Hook_Collector extends Stopwatch_Collector { /** @var Hook_Formatter */ protected $formatter; + /** @var array $calls Tracks number of calls for recurrent events. */ + private $calls = []; + /** * @param Stopwatch $stopwatch Stopwatch instance. * @param Hook_Event_Config_Interface[] $event_configs Starts and stops configuration. @@ -97,6 +100,8 @@ class Hook_Collector extends Stopwatch_Collector { if ( '' !== $start ) { add_action( $start, function ( $input = null ) use ( $event, $category, $start, $stop ) { + $event .= $this->get_count_suffix( $event, true ); + if ( 'Sidebar' === $event ) { $event = $input; } @@ -115,6 +120,8 @@ class Hook_Collector extends Stopwatch_Collector { if ( '' !== $stop ) { add_action( $stop, function ( $input = null ) use ( $event ) { + $event .= $this->get_count_suffix( $event ); + if ( 'Sidebar' === $event ) { $event = $input; } @@ -126,6 +133,29 @@ class Hook_Collector extends Stopwatch_Collector { } } + /** + * Get the suffix to use if event occurs multiple times. + * + * @param string $event Event name. + * @param boolean $increment Flag to increment count. + * + * @return string + */ + private function get_count_suffix( string $event, bool $increment = false ): string { + + if ( ! isset( $this->calls[ $event ] ) ) { + $this->calls[ $event ] = 0; + } + + if ( $increment ) { + $this->calls[ $event ] ++; + } + + $count = (int) $this->calls[ $event ]; + + return $count > 1 ? " ({$count})" : ''; + } + /** * When theme is done possibly add vendor-specific events. */