diff --git a/CHANGELOG.md b/CHANGELOG.md index 4e29392..65922b4 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -11,6 +11,7 @@ and this project adheres to [Semantic Versioning](http://semver.org/). - new format of hook events - sidebar tracking - list of callbacks to hook events +- Server Timing output for Ajax and REST APIs ### Changed - required PHP version to 7.1 diff --git a/src/Manager/Server_Timing_Manager.php b/src/Manager/Server_Timing_Manager.php new file mode 100644 index 0000000..eb5593c --- /dev/null +++ b/src/Manager/Server_Timing_Manager.php @@ -0,0 +1,71 @@ +laps = $laps; + + add_action( 'admin_init', [ $this, 'send_timing_header' ], PHP_INT_MAX ); + add_action( 'rest_pre_serve_request', [ $this, 'send_timing_header' ] ); + } + + /** + * Sends Server Timing API header with records data. + * + * @param mixed $input Pass-through input for attaching to a filter hook. + * + * @return mixed + */ + public function send_timing_header( $input ) { + + if ( headers_sent() ) { + return $input; + } + + $ajax = defined( 'DOING_AJAX' ) && DOING_AJAX; + $rest = defined( 'REST_REQUEST' ) && REST_REQUEST; + + if ( ! $ajax && ! $rest ) { + return $input; + } + + // This will be false in REST API w/o nonce, even with valid cookie. Might make sense to filter to true in dev. + if ( ! apply_filters( 'laps_can_see', current_user_can( 'manage_options' ) ) ) { + return $input; + } + + $records = $this->laps['records']; + $header = ''; + + /** @var Record_Interface $record */ + foreach ( $records as $record ) { + $duration = $record->get_duration() * 1000; + + if ( $duration < 1 ) { + continue; + } + + $header .= sprintf( '%s;dur=%d;desc="%s", ', $record->get_category(), $duration, $record->get_name() ); + } + + header( 'Server-Timing: ' . $header ); + + return $input; + } +} diff --git a/src/Plugin.php b/src/Plugin.php index 4af88ba..c392b85 100644 --- a/src/Plugin.php +++ b/src/Plugin.php @@ -68,10 +68,6 @@ class Plugin extends Container { */ public function run(): void { - if ( \defined( 'DOING_AJAX' ) && DOING_AJAX ) { - return; - } - foreach ( $this->providers as $provider ) { if ( $provider instanceof Bootable_Provider_Interface ) { diff --git a/src/Provider/Manager_Provider.php b/src/Provider/Manager_Provider.php index 78d4b2d..ac5760f 100644 --- a/src/Provider/Manager_Provider.php +++ b/src/Provider/Manager_Provider.php @@ -5,6 +5,7 @@ namespace Rarst\Laps\Provider; use Pimple\Container; use Pimple\ServiceProviderInterface; +use Rarst\Laps\Manager\Server_Timing_Manager; use Rarst\Laps\Plugin; use Rarst\Laps\Manager\Asset_Manager; use Rarst\Laps\Manager\Load_Order_Manager; @@ -25,6 +26,7 @@ class Manager_Provider implements ServiceProviderInterface, Bootable_Provider_In new Load_Order_Manager(), new Asset_Manager(), new Toolbar_Manager( $laps ), + new Server_Timing_Manager( $laps ), ]; }; }