Get use statement from class

和自甴很熟 提交于 2019-12-05 03:19:24

Seeing as no one has answered, I assume there is not an easy way to achieve this. I have therefore created my own class called ExtendedReflectionClass which achieves what I need.

I have created a gist with the class file and a readme, which is at the bottom so get scrolling!.

ExtendedReflectionClass

Usage example:

require 'ExtendedReflectionClass.php';
require 'MyCustomClass.php';

$class = new ExtendedReflectionClass('MyNamespace\Test\MyCustomClass');

$class->getUseStatements();    
// [
//     [
//         'class' => 'FooNamespace\FooClass',
//         'as' => 'FooClass'
//     ],
//     [
//         'class' => 'BarNamespace\BarClass',
//         'as' => 'Bar'
//     ],
//     [
//         'class' => 'BazNamespace\BazClass',
//         'as' => 'BazSpecial'
//     ]
// ]

$class->hasUseStatement('FooClass'); // true
$class->hasUseStatement('BarNamespace\BarClass'); // true
$class->hasUseStatement('BazSpecial'); // true

$class->hasUseStatement('SomeNamespace\SomeClass'); // false

I use the TokenFinderTool for that.

Basically, it uses tokens to extract the use statements.

As far as I know, \Reflection objects in php unfortunately don't have such a method yet.

The code below extracts the use import statements from a file, using the TokenFinder tool.

$tokens = token_get_all(file_get_contents("/path/to/MyCompany/MyClass.php"));
a(TokenFinderTool::getUseDependencies($tokens));

Will output:

array (size=9)
  0 => string 'Bat\CaseTool' (length=12)
  1 => string 'Bat\FileSystemTool' (length=18)
  2 => string 'Bat\StringTool' (length=14)
  3 => string 'Bat\ValidationTool' (length=18)
  4 => string 'CopyDir\AuthorCopyDirUtil' (length=25)
  5 => string 'PhpBeast\AuthorTestAggregator' (length=29)
  6 => string 'PhpBeast\PrettyTestInterpreter' (length=30)
  7 => string 'PhpBeast\Tool\ComparisonErrorTableTool' (length=38)
  8 => string 'Tiphaine\TiphaineTool' (length=21)

Note: if you have a class name only, you can use this snippet instead:

$o = new \ReflectionClass($className);
$tokens = token_get_all(file_get_contents($$o->getFileName()));
$useStatements = TokenFinderTool::getUseDependencies($tokens);
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!