Skip to content

Commit

Permalink
Merge pull request #56 from 10up/enhancement/add_valid_strategy_function
Browse files Browse the repository at this point in the history
is_valid_strategy and _doing_wrong check
  • Loading branch information
10upsimon authored Apr 21, 2023
2 parents b92f5be + 8549c52 commit 281aadc
Show file tree
Hide file tree
Showing 2 changed files with 49 additions and 1 deletion.
30 changes: 29 additions & 1 deletion src/wp-includes/class-wp-scripts.php
Original file line number Diff line number Diff line change
Expand Up @@ -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.
*
Expand All @@ -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;
}

/**
Expand Down
20 changes: 20 additions & 0 deletions tests/phpunit/tests/dependencies/scripts.php
Original file line number Diff line number Diff line change
Expand Up @@ -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 = "<script type='text/javascript' src='/defaults.js' id='invalid-strategy-js'></script>\n";

$this->assertSame( $expected, $output );
}

/**
* Test script concatenation with deferred main script.
*
Expand Down

0 comments on commit 281aadc

Please sign in to comment.