diff --git a/src/wp-includes/load.php b/src/wp-includes/load.php index 27c58b57dd671..31437fe4ee60d 100644 --- a/src/wp-includes/load.php +++ b/src/wp-includes/load.php @@ -1789,6 +1789,24 @@ function wp_doing_cron() { return apply_filters( 'wp_doing_cron', defined( 'DOING_CRON' ) && DOING_CRON ); } +/** + * Determines whether the current request is a WP-CLI request. + * + * @since {{VERSION}} + * + * @return bool True if it's a WP-CLI request, false otherwise. + */ +function wp_doing_cli() { + /** + * Filters whether the current request is a WP-CLI request. + * + * @since {{VERSION}} + * + * @param bool $wp_doing_cli Whether the current request is a WP-CLI request. + */ + return apply_filters( 'wp_doing_cli', defined( 'WP_CLI' ) && WP_CLI ); +} + /** * Checks whether the given variable is a WordPress Error. * diff --git a/tests/phpunit/tests/functions/wpDoingCli.php b/tests/phpunit/tests/functions/wpDoingCli.php new file mode 100644 index 0000000000000..fa3ab9a7c9d52 --- /dev/null +++ b/tests/phpunit/tests/functions/wpDoingCli.php @@ -0,0 +1,67 @@ +assertFalse( wp_doing_cli() ); + } + + /** + * Tests that wp_doing_cli() returns true when forced via the filter. + * + * @ticket 65043 + */ + public function test_wp_doing_cli_returns_true_when_filtered() { + add_filter( 'wp_doing_cli', '__return_true' ); + $result = wp_doing_cli(); + remove_filter( 'wp_doing_cli', '__return_true' ); + + $this->assertTrue( $result ); + } + + /** + * Tests that wp_doing_cli() returns false when forced via the filter. + * + * @ticket 65043 + */ + public function test_wp_doing_cli_returns_false_when_filtered() { + add_filter( 'wp_doing_cli', '__return_false' ); + $result = wp_doing_cli(); + remove_filter( 'wp_doing_cli', '__return_false' ); + + $this->assertFalse( $result ); + } + + /** + * Tests that wp_doing_cli() applies the wp_doing_cli filter. + * + * @ticket 65043 + */ + public function test_wp_doing_cli_applies_filter() { + $filter_called = false; + + add_filter( + 'wp_doing_cli', + function ( $doing_cli ) use ( &$filter_called ) { + $filter_called = true; + return $doing_cli; + } + ); + + wp_doing_cli(); + + $this->assertTrue( $filter_called, 'The wp_doing_cli filter should be applied.' ); + } +}