jerowork / class-dependencies-parser
Parse all dependencies (FQN) used in an object (e.g. class, trait, interface)
0.5.1
2023-02-23 18:14 UTC
Requires
- php: ^8.1
- nikic/php-parser: ^4.15
Requires (Dev)
- friendsofphp/php-cs-fixer: ^3.13
- maglnet/composer-require-checker: ^4.5
- phpro/grumphp-shim: ^1.14
- phpstan/phpstan: ^1.9
- phpunit/phpunit: ^9.5 || ^10.0
- scrutinizer/ocular: ^1.9
README
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