Skip to content

Commit

Permalink
added PhpReflection::getUseStatements()
Browse files Browse the repository at this point in the history
  • Loading branch information
dg committed May 23, 2016
1 parent 9b9b32c commit 7f8259b
Show file tree
Hide file tree
Showing 2 changed files with 40 additions and 10 deletions.
30 changes: 20 additions & 10 deletions src/DI/PhpReflection.php
Original file line number Diff line number Diff line change
Expand Up @@ -18,10 +18,6 @@ class PhpReflection
{
use Nette\StaticClass;

/** @var array for expandClassName() */
private static $cache = [];


/**
* Returns an annotation value.
* @return string|NULL
Expand Down Expand Up @@ -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]];
Expand All @@ -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)
{
Expand Down
20 changes: 20 additions & 0 deletions tests/DI/PhpReflection.expandClassName.phpt
Original file line number Diff line number Diff line change
Expand Up @@ -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'))
);

0 comments on commit 7f8259b

Please sign in to comment.