From 7f8259b9d33e218ec48b85e8b179d6f7568552bb Mon Sep 17 00:00:00 2001 From: David Grudl Date: Thu, 12 Mar 2015 00:09:08 +0100 Subject: [PATCH] added PhpReflection::getUseStatements() --- src/DI/PhpReflection.php | 30 ++++++++++++++------- tests/DI/PhpReflection.expandClassName.phpt | 20 ++++++++++++++ 2 files changed, 40 insertions(+), 10 deletions(-) diff --git a/src/DI/PhpReflection.php b/src/DI/PhpReflection.php index 5122051b2..1c0988912 100644 --- a/src/DI/PhpReflection.php +++ b/src/DI/PhpReflection.php @@ -18,10 +18,6 @@ class PhpReflection { use Nette\StaticClass; - /** @var array for expandClassName() */ - private static $cache = []; - - /** * Returns an annotation value. * @return string|NULL @@ -127,11 +123,7 @@ public static function expandClassName($name, \ReflectionClass $rc) return ltrim($name, '\\'); } - $uses = & self::$cache[$rc->getName()]; - if ($uses === NULL) { - self::$cache = self::parseUseStatemenets(file_get_contents($rc->getFileName()), $rc->getName()) + self::$cache; - $uses = & self::$cache[$rc->getName()]; - } + $uses = self::getUseStatements($rc); $parts = explode('\\', $name, 2); if (isset($uses[$parts[0]])) { $parts[0] = $uses[$parts[0]]; @@ -146,10 +138,28 @@ public static function expandClassName($name, \ReflectionClass $rc) } + /** + * @return array of [alias => class] + */ + public static function getUseStatements(\ReflectionClass $class) + { + static $cache = []; + if (!isset($cache[$name = $class->getName()])) { + if ($class->isInternal()) { + $cache[$name] = []; + } else { + $code = file_get_contents($class->getFileName()); + $cache = self::parseUseStatemenets($code, $name) + $cache; + } + } + return $cache[$name]; + } + + /** * Parses PHP code. * @param string - * @return array + * @return array of [class => [alias => class, ...]] */ public static function parseUseStatemenets($code, $forClass = NULL) { diff --git a/tests/DI/PhpReflection.expandClassName.phpt b/tests/DI/PhpReflection.expandClassName.phpt index 74ea5a886..ee80cb3b8 100644 --- a/tests/DI/PhpReflection.expandClassName.phpt +++ b/tests/DI/PhpReflection.expandClassName.phpt @@ -115,3 +115,23 @@ foreach ($cases as $alias => $fqn) { Assert::same($fqn[0], PhpReflection::expandClassName($alias, $rcFoo)); Assert::same($fqn[1], PhpReflection::expandClassName($alias, $rcBar)); } + + +Assert::same( + ['C' => 'A\B'], + PhpReflection::getUseStatements(new ReflectionClass('Test')) +); + +Assert::same( + [], + PhpReflection::getUseStatements(new ReflectionClass('Test\Space\Foo')) +); + +Assert::same( + ['AAA' => 'AAA', 'B' => 'BBB', 'DDD' => 'CCC\DDD', 'F' => 'EEE\FFF', 'G' => 'GGG'], + PhpReflection::getUseStatements(new ReflectionClass('Test\Space\Bar')) +); +Assert::same( + [], + PhpReflection::getUseStatements(new ReflectionClass('stdClass')) +);