diff --git a/src/wp-includes/class-wp-scripts.php b/src/wp-includes/class-wp-scripts.php index e627f28eb4fbb..02b925578f052 100644 --- a/src/wp-includes/class-wp-scripts.php +++ b/src/wp-includes/class-wp-scripts.php @@ -871,6 +871,18 @@ private function get_dependents( $handle ) { return $dependents; } + /** + * Determines if a script loading strategy is valid. + * + * @param string $strategy A script loading strategy. + * @return bool True if the strategy is of an allowed type, false otherwise. + */ + private function is_valid_strategy( $strategy ) { + $allowed_strategies = array( 'blocking', 'defer', 'async' ); + + return in_array( $strategy, $allowed_strategies, true ); + } + /** * Get the strategy assigned during script registration. * @@ -879,8 +891,24 @@ private function get_dependents( $handle ) { */ private function get_intended_strategy( $handle ) { $script_args = $this->get_data( $handle, 'script_args' ); + $strategy = isset( $script_args['strategy'] ) ? $script_args['strategy'] : false; + + if ( $strategy && ! $this->is_valid_strategy( $strategy ) ) { + _doing_it_wrong( + __METHOD__, + sprintf( + /* translators: 1: $strategy, 2: $handle */ + __( 'Invalid strategy `%1$s` defined for `%2$s` during script registration.' ), + $strategy, + $handle + ), + '6.3.0' + ); + + return false; + } - return isset( $script_args['strategy'] ) ? $script_args['strategy'] : false; + return $strategy; } /** diff --git a/tests/phpunit/tests/dependencies/scripts.php b/tests/phpunit/tests/dependencies/scripts.php index 6b267c9623d99..7670f0bb37096 100644 --- a/tests/phpunit/tests/dependencies/scripts.php +++ b/tests/phpunit/tests/dependencies/scripts.php @@ -628,6 +628,26 @@ public function test_get_normalized_script_args() { $this->assertSame( $expected_args, $wp_scripts->get_data( 'footer-old', 'script_args' ) ); } + /** + * Test script strategy doing it wrong. + * + * For an invalid strategy defined during script registration, default to a blocking strategy. + * + * @ticket 12009 + */ + public function test_script_strategy_doing_it_wrong() { + $this->setExpectedIncorrectUsage( 'WP_Scripts::get_intended_strategy' ); + + wp_register_script( 'invalid-strategy', '/defaults.js', array(), null, array( 'strategy' => 'random-strategy' ) ); + wp_enqueue_script( 'invalid-strategy' ); + + $output = get_echo( 'wp_print_scripts' ); + + $expected = "\n"; + + $this->assertSame( $expected, $output ); + } + /** * Test script concatenation with deferred main script. *