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
29 changes: 29 additions & 0 deletions features/profile-stage.feature
Original file line number Diff line number Diff line change
Expand Up @@ -171,3 +171,32 @@ Feature: Profile the template render stage
| hook |
| init |
| wp_loaded:after |

@require-wp-4.0
Scenario: Admin URL runs as a backend request and skips frontend stages
Given a WP install

When I run `wp profile stage --url=example.com/wp-admin/ --context=admin --fields=stage`
Then STDOUT should be a table containing rows:
| stage |
| bootstrap |
And STDOUT should not contain:
"""
main_query
"""
And STDOUT should not contain:
"""
template
"""
And STDERR should be empty

@require-wp-4.0
Scenario: Admin URL without --context=admin emits an error
Given a WP install

When I try `wp profile stage --url=example.com/wp-admin/ --fields=stage`
Then STDERR should contain:
"""
Profiling an admin URL requires --context=admin.
"""
And the return code should be 1
24 changes: 24 additions & 0 deletions src/Profiler.php
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,8 @@ class Profiler {
private $tick_cache_hit_offset = null;
private $tick_cache_miss_offset = null;

private $is_admin_request = false;

public function __construct( $type, $focus ) {
$this->type = $type;
$this->focus = $focus;
Expand Down Expand Up @@ -77,6 +79,23 @@ public function get_loggers() {
* Run the profiler against WordPress
*/
public function run() {
$url = WP_CLI::get_runner()->config['url'];
$path = '';
if ( ! empty( $url ) ) {
$parsed_url = WP_CLI\Utils\parse_url( $url );
if ( false !== $parsed_url && isset( $parsed_url['path'] ) ) {
$path = $parsed_url['path'];
} else {
// Fallback for cases where $url is just a path.
$path = $url;
}
}
$this->is_admin_request = ! empty( $path ) && (bool) preg_match( '#/wp-admin(/|$|\?)#i', $path );

if ( $this->is_admin_request && 'admin' !== WP_CLI::get_runner()->config['context'] ) {
WP_CLI::error( 'Profiling an admin URL requires --context=admin.' );
}

WP_CLI::add_wp_hook(
'muplugins_loaded',
function () {
Expand Down Expand Up @@ -437,6 +456,11 @@ private function load_wordpress_with_template() {
$this->loggers[] = $logger;
}

// Skip main_query and template stages for admin requests.
if ( $this->is_admin_request ) {
return;
}

// Set up main_query main WordPress query.
if ( 'stage' === $this->type ) {
if ( 'main_query' === $this->focus ) {
Expand Down