phpdocumentor/reflection
Static PHP code reflection library that parses one or more files (no execution) to build an object graph of your application's structure, including DocBlocks. Supports analyzing PHP versions from 5.2 up to your installed PHP version; useful for reflecting whole projects.
## Getting Started
### Minimal Setup
1. **Installation**:
```bash
composer require phpdocumentor/reflection:~7.0
Ensure vendor/autoload.php is included in your project.
First Use Case: Reflect a single file to inspect its structure:
use phpDocumentor\Reflection\Php\ProjectFactory;
use phpDocumentor\Reflection\File\LocalFile;
$factory = ProjectFactory::createInstance();
$project = $factory->create(
'My Project',
[new LocalFile('path/to/YourClass.php')]
);
// Access the first class in the file
$class = $project->getFiles()[0]->getClasses()[0];
echo $class->getName(); // Output: YourClass
Key Entry Points:
ProjectFactory::createInstance(): Initialize with default parser (PHP7 preferred, PHP5 fallback).$factory->create(): Parse files into a Project object.$project->getFiles(): Retrieve parsed files with their classes, traits, interfaces, and namespaces.Workflow:
LocalFile objects:
$files = [];
foreach (glob(app_path('*').'/*.php') as $file) {
$files[] = new LocalFile($file);
}
$project = $factory->create('Laravel App', $files);
Integration Tip:
Project object to avoid reprocessing:
$cacheKey = 'reflection_project_'.md5(filemtime(app_path('bootstrap/app.php')));
$project = cache()->remember($cacheKey, now()->addHours(1), function () use ($factory) {
return $factory->create('Laravel App', $files);
});
Common Operations:
$class = $project->getFiles()[0]->getClasses()[0];
$methods = $class->getMethods(); // Array of Method objects
$properties = $class->getProperties(); // Array of Property objects
$method = $class->getMethod('handleRequest');
$parameters = $method->getParameters(); // Array of Parameter objects
$returnType = $method->getReturnType(); // Type object (e.g., `string`, `array<int, Model>`)
$docBlock = $class->getDocBlock();
$tags = $docBlock->getTags(); // Array of Tag objects (e.g., `@param`, `@return`)
Laravel-Specific Example:
$controller = $project->findClass('App\Http\Controllers\YourController');
$method = $controller->getMethod('__invoke');
foreach ($method->getParameters() as $param) {
echo "Parameter: {$param->getName()} (Type: {$param->getType()->__toString()})\n";
}
Advanced Use Case:
$parameter = $method->getParameters()[0];
$defaultValue = $parameter->getDefaultValue();
$resolvedType = $defaultValue->getType(); // Returns a `Type` object
$defaultValue = new \phpDocumentor\Reflection\Php\Value\Value([
'key' => 'value',
'items' => [1, 2, 3]
]);
$type = $defaultValue->getType(); // Returns `array{string, int}`
Integration Tip:
TypeResolver to validate or transform types:
use phpDocumentor\TypeResolver;
$resolver = new TypeResolver();
$type = $resolver->resolve($parameter->getType());
Extend Functionality:
$factory = ProjectFactory::createInstance();
$factory->setFileStrategy(new class implements \phpDocumentor\Reflection\Php\FileStrategy {
public function process(\phpDocumentor\Reflection\File\File $file) {
if (str_contains($file->getPath(), 'tests') || str_contains($file->getPath(), 'vendor')) {
return null; // Skip
}
return $file;
}
});
Modify Reflection Data:
$factory->addMiddleware(new class implements \phpDocumentor\Reflection\Middleware\Middleware {
public function execute(\phpDocumentor\Reflection\Php\Project $project) {
foreach ($project->getFiles() as $file) {
foreach ($file->getClasses() as $class) {
$class->setCustomProperty('is_laravel_service', str_contains($class->getName(), 'Service'));
}
}
return $project;
}
});
phpDocumentor\Reflection\Type was refactored. Update code using:
// Old (v6):
$type = $parameter->getType(); // Might return mixed types
// New (v7):
$type = $parameter->getType(); // Always returns a `Type` object (e.g., `String_`, `Array_`)
"new stdClass()") are now Expression objects. Use:
$expression = $parameter->getDefaultValue()->getExpression();
$type = $expression->getType(); // Resolve type from expression
try {
$project = $factory->create('Project', [$file]);
} catch (\phpDocumentor\Reflection\Exception $e) {
echo "Error in {$e->getFile()}:{$e->getLine()}: {$e->getMessage()}\n";
}
$factory->setParserOptions(['prettyPrint' => true]); // Reduce memory for complex files
$factory = ProjectFactory::createInstance('php5');
Project objects or individual elements (e.g., classes) to avoid reprocessing:
cache()->forever('reflection_class_'.$class->getFqsen(), $class);
~7.0:
composer require phpdocumentor/reflection:~7.0
@custom) won’t throw exceptions but return InvalidTag objects:
$docBlock = $class->getDocBlock();
foreach ($docBlock->getTags() as $tag) {
if ($tag instanceof \phpDocumentor\Reflection\DocBlock\Tag\InvalidTag) {
echo "Invalid tag: {$tag->getContent()}\n";
}
}
array{...} syntax):
$factory->setParserOptions(['phpVersion' => '8.5']);
\phpDocumentor\Reflection\Php\Factory\AbstractFactory to handle edge cases (e.g., custom attributes).\phpDocumentor\TypeResolver\Resolver for custom type logic (e.g., Laravel collections):
$resolver = new class extends \phpDocumentor\TypeResolver\Resolver {
protected function resolveCollectionType(\phpDocumentor\Reflection\Type $type) {
return new \phpDocumentor\Reflection\Type\Object_('
How can I help you explore Laravel packages today?