From 5750499c5e8589130878010bc7cb18e813d7b6dc Mon Sep 17 00:00:00 2001 From: Timm Friebe Date: Sat, 30 Sep 2023 19:21:54 +0200 Subject: [PATCH] Fix `FromAttributes::imports()` for classes created inside `eval` --- ChangeLog.md | 5 +++++ src/main/php/lang/meta/FromAttributes.class.php | 8 ++++++-- .../lang/reflection/unittest/FromAttributesTest.class.php | 6 ++++++ 3 files changed, 17 insertions(+), 2 deletions(-) diff --git a/ChangeLog.md b/ChangeLog.md index 5efec43..d644bdd 100755 --- a/ChangeLog.md +++ b/ChangeLog.md @@ -3,6 +3,11 @@ XP Reflection ChangeLog ## ?.?.? / ????-??-?? +## 2.14.1 / 2023-09-30 + +* Fixed `FromAttributes::imports()` for classes created inside `eval` + (@thekid) + ## 2.14.0 / 2023-09-23 * Added support for partial meta information - @thekid diff --git a/src/main/php/lang/meta/FromAttributes.class.php b/src/main/php/lang/meta/FromAttributes.class.php index 2f58229..4c77402 100755 --- a/src/main/php/lang/meta/FromAttributes.class.php +++ b/src/main/php/lang/meta/FromAttributes.class.php @@ -58,14 +58,18 @@ public function ofParameter($method, $reflect) { /** * Returns imports used in the class file the given class was declared in * - * @param \ReflectionClass $reflect + * @param ReflectionClass $reflect * @return [:string] */ public function imports($reflect) { static $break= [T_CLASS => true, T_INTERFACE => true, T_TRAIT => true, 372 /* T_ENUM */ => true]; static $types= [T_WHITESPACE => true, 44 => true, 59 => true, 123 => true]; - $tokens= PhpToken::tokenize(file_get_contents($reflect->getFileName())); + // Exclude classes declared inside eval(), their declaration is not accessible + $file= $reflect->getFileName(); + if (false !== strpos($file, ': eval')) return []; + + $tokens= PhpToken::tokenize(file_get_contents($file)); $imports= []; for ($i= 0, $s= sizeof($tokens); $i < $s; $i++) { if (isset($break[$tokens[$i]->id])) break; diff --git a/src/test/php/lang/reflection/unittest/FromAttributesTest.class.php b/src/test/php/lang/reflection/unittest/FromAttributesTest.class.php index 8235639..aee9dfe 100755 --- a/src/test/php/lang/reflection/unittest/FromAttributesTest.class.php +++ b/src/test/php/lang/reflection/unittest/FromAttributesTest.class.php @@ -31,6 +31,12 @@ public function imports() { ); } + #[Test] + public function imports_from_eval() { + $name= eval('class FromAttributesTest_eval { } return FromAttributesTest_eval::class;'); + Assert::equals([], (new FromAttributes())->imports(new ReflectionClass($name))); + } + #[Test] public function evaluate_constant() { Assert::equals(