Skip to content

Commit

Permalink
Catch throwables when evaluating state callbacks
Browse files Browse the repository at this point in the history
  • Loading branch information
DAreRodz committed May 24, 2024
1 parent a1fb279 commit 3f571c0
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 4 deletions.
16 changes: 15 additions & 1 deletion src/wp-includes/interactivity-api/class-wp-interactivity-api.php
Original file line number Diff line number Diff line change
Expand Up @@ -485,7 +485,21 @@ private function evaluate( $directive_value ) {
}

if ( $current instanceof Closure ) {
$current = $current();
try {
$current = $current();
} catch ( Throwable $e ) {
_doing_it_wrong(
__METHOD__,
sprintf(
/* translators: 1: Path pointing to an Interactivity API state property, 2: Namespace for an Interactivity API store. */
__( 'Uncaught error executing a derived state callback with path "%1$s" and namespace "%2$s".' ),
$path,
$ns
),
'6.6.0'
);
return null;
}
}

// Returns the opposite if it contains a negation operator (!).
Expand Down
23 changes: 20 additions & 3 deletions tests/phpunit/tests/interactivity-api/wpInteractivityAPI.php
Original file line number Diff line number Diff line change
Expand Up @@ -994,9 +994,9 @@ public function test_process_directives_does_not_change_inner_html_in_math() {
private function evaluate( $directive_value ) {
$generate_state = function ( $name ) {
return array(
'key' => $name,
'nested' => array( 'key' => $name . '-nested' ),
'derived' => function () {
'key' => $name,
'nested' => array( 'key' => $name . '-nested' ),
'derived' => function () {
$state = wp_interactivity_state();
$context = wp_interactivity_get_context();
return 'Derived state: ' .
Expand All @@ -1005,6 +1005,9 @@ private function evaluate( $directive_value ) {
'Derived context: ' .
$context['key'];
},
'derivedThatThrows' => function () {
throw new Error( 'Something bad happened.' );
},
);
};
$this->interactivity->state( 'myPlugin', $generate_state( 'myPlugin-state' ) );
Expand Down Expand Up @@ -1142,6 +1145,20 @@ public function test_evaluate_derived_state() {
$this->assertEquals( "Derived state: myPlugin-state\nDerived context: myPlugin-context", $result );
}


/**
* Tests the `evaluate` method for derived state functions.
*
* @ticket 61037
*
* @covers ::evaluate
* @expectedIncorrectUsage WP_Interactivity_API::evaluate
*/
public function test_evaluate_derived_state_that_throws() {
$result = $this->evaluate( 'state.derivedThatThrows' );
$this->assertEquals( null, $result );
}

/**
* Tests the `kebab_to_camel_case` method.
*
Expand Down

0 comments on commit 3f571c0

Please sign in to comment.