Skip to content

Commit

Permalink
Remove namespace from closure names
Browse files Browse the repository at this point in the history
  • Loading branch information
westonruter committed Nov 4, 2024
1 parent 5fda4ab commit 58cfe0a
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 4 deletions.
19 changes: 17 additions & 2 deletions src/DevTools/CallbackReflection.php
Original file line number Diff line number Diff line change
Expand Up @@ -110,17 +110,32 @@ public function get_source( $callback ) {
if ( $reflection instanceof ReflectionMethod ) {
$source['function'] = $reflection->getDeclaringClass()->getName() . '::' . $reflection->getName();
} else {
$function_name = $reflection->getName();

/*
* In PHP 8.4, a closure's string representation changes from {closure} to include the function that contained
* the closure, like {closure:Test_AMP_Validation_Manager::test_decorate_shortcode_and_filter_source():1831}.
* It can even indicate closure nesting like {closure:{closure:Test_AMP_Validation_Manager::get_locate_sources_data():883}:886}.
* So these are normalized here.
*/
$source['function'] = preg_replace(
$function_name = preg_replace(
'/\{closure.*}/',
'{closure}',
$reflection->getName()
$function_name
);

/*
* Additionally, in PHP 8.4 the namespace no longer prefixes the closure. So this is now removed
* for consistency across all PHP versions, replacing AmpProject\AmpWP\Tests\DevTools\{closure}
* with just {closure}.
*/
$function_name = preg_replace(
'/(\w+\\\\)+(?=\{)/',
'',
$function_name
);

$source['function'] = $function_name;
}

return $source;
Expand Down
3 changes: 1 addition & 2 deletions tests/php/src/DevTools/CallbackReflectionTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -208,7 +208,7 @@ public function data_get_source() {
],
'plugin_closure' => [
function () {},
__NAMESPACE__ . '\{closure}',
'{closure}',
'amp',
'plugin',
'tests/php/src/DevTools/CallbackReflectionTest.php',
Expand Down Expand Up @@ -246,7 +246,6 @@ public function test_get_source( $function, $source_function, $name, $type, $fil
/** @var ReflectionFunction $reflection */
$reflection = $source['reflection'];
$this->assertInstanceOf( $reflection_class, $reflection );
$this->assertEquals( preg_replace( '/.*::/', '', $source['function'] ), $reflection->getName() );
}

/**
Expand Down

0 comments on commit 58cfe0a

Please sign in to comment.