Awesome
class-dependencies-parser
Parse all dependencies (FQN) used in a class (e.g. class, trait, interface, enum).
Installation
Install via Composer:
composer require jerowork/class-dependencies-parser
Usage
use Jerowork\ClassDependenciesParser\PhpParser\NodeTraverserFactory;
use Jerowork\ClassDependenciesParser\PhpParser\PhpParserClassDependenciesParser;
use PhpParser\ParserFactory;
// Setup parser
$parser = new PhpParserClassDependenciesParser(
(new ParserFactory())->create(ParserFactory::PREFER_PHP7),
new NodeTraverserFactory(),
);
// Parse file
$classDependencies = $parser->parse('/Path/To/file.php');
// Output dependencies
print_r(
$classDependencies->getDependencyList(),
);
// This will output e.g.:
[
'Some/Namespace/Class',
'Another/Namespace/Trait',
// ...
]
DI service definition
As a good practice we should always 'program to interfaces, not implementations', you should add this to your DI container.
PSR-11 Container example:
use Jerowork\ClassDependenciesParser\ClassDependenciesParser;
use Jerowork\ClassDependenciesParser\PhpParser\NodeTraverserFactory;
use Jerowork\ClassDependenciesParser\PhpParser\PhpParserClassDependenciesParser;
use PhpParser\ParserFactory;
return [
ClassDependenciesParser::class => static function (ContainerInterface $container): ClassDependenciesParser {
return new PhpParserClassDependenciesParser(
(new ParserFactory())->create(ParserFactory::PREFER_PHP7),
new NodeTraverserFactory(),
);
},
];
Symfony YAML-file example:
services:
_defaults:
autowire: true
autoconfigure: true
Jerowork\ClassDependenciesParser\ClassDependenciesParser:
class: Jerowork\ClassDependenciesParser\PhpParser\PhpParserClassDependenciesParser
Jerowork\ClassDependenciesParser\PhpParser\NodeTraverserFactory: ~
PhpParser\ParserFactory: ~
PhpParser\Parser:
factory: ['@PhpParser\ParserFactory', 'create']
arguments:
$kind: 1