spatie/php-type-graph
Build a graph of all PHP types in your project. Analyze classes, interfaces, enums, and their relationships to understand your codebase structure, dependencies, and type usage. Useful for architecture insights, tooling, and visualization (WIP).
Installation Require the package via Composer:
composer require spatie/php-type-graph --dev
Run the type-graph:generate Artisan command to generate the type graph:
php artisan type-graph:generate
This creates a type-graph.json file in your project root.
First Use Case Use the generated graph to analyze dependencies between types (classes, interfaces, traits) in your project. For example, inspect how a model class depends on other types:
$graph = new \Spatie\TypeGraph\TypeGraph('type-graph.json');
$dependencies = $graph->getDependenciesForType('App\Models\User');
type-graph.json for the full dependency graph.php artisan type-graph:generate --help to explore options like --exclude or --output.Dependency Analysis Use the graph to visualize or programmatically inspect how types interact. Example:
$graph = new \Spatie\TypeGraph\TypeGraph('type-graph.json');
$allDependencies = $graph->getAllDependencies(); // Returns a nested array of dependencies.
Integration with Tests Add assertions in PHPUnit to verify type dependencies (e.g., ensure a service doesn’t depend on a deprecated class):
public function testNoDeprecatedDependencies()
{
$graph = new \Spatie\TypeGraph\TypeGraph('type-graph.json');
$this->assertFalse($graph->hasDependency('App\Services\NewService', 'App\Legacy\DeprecatedClass'));
}
CI/CD Checks Automate dependency checks in GitHub Actions or GitLab CI:
# .github/workflows/type-graph-check.yml
jobs:
type-graph:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- run: composer install
- run: php artisan type-graph:generate
- run: php scripts/check-forbidden-dependencies.php
Refactoring Safety Net Generate the graph before/after refactoring to spot unintended dependency changes.
php artisan type-graph:generate --output=before-refactor.json
# Refactor code...
php artisan type-graph:generate --output=after-refactor.json
Onboarding New Developers Share the graph to help new team members understand the project’s architecture. Example:
$graph->getTypesByNamespace('App\Models'); // List all models and their dependencies.
Custom Exclusions
Exclude specific directories or types from the graph using the --exclude flag:
php artisan type-graph:generate --exclude="vendor/*" --exclude="tests/*"
Extend the Graph
Subclass \Spatie\TypeGraph\TypeGraph to add custom logic (e.g., highlight circular dependencies):
class CustomTypeGraph extends \Spatie\TypeGraph\TypeGraph {
public function hasCircularDependencies(string $type): bool {
// Custom implementation.
}
}
Performance with Large Codebases
Generating the graph for projects with thousands of classes may be slow. Use --exclude to limit scope:
php artisan type-graph:generate --exclude="app/Helpers/*"
False Positives in Dependencies The graph may include indirect dependencies (e.g., via traits or magic methods). Filter results carefully:
$directDependencies = $graph->getDirectDependenciesForType('App\Models\User');
Outdated Graphs Always regenerate the graph before critical checks, as it reflects the state of the codebase at generation time.
Verify Graph Accuracy
Manually inspect a subset of the type-graph.json output to ensure it matches your expectations. Example:
{
"App\Models\User": {
"dependsOn": ["App\Contracts\Authenticatable", "Illuminate\Database\Eloquent\Model"]
}
}
Handle Missing Types If a type isn’t found, check for typos or ensure the class is autoloaded (e.g., not in a non-PSR-4 namespace).
Custom Output Path
Change the default output path via the --output flag:
php artisan type-graph:generate --output=storage/type-graph.json
Namespace Filtering
Use --namespace to focus on specific parts of the project:
php artisan type-graph:generate --namespace="App\\"
Custom Graph Formatters Extend the package to output the graph in alternative formats (e.g., DOT for Graphviz):
$graph->toDot()->saveToFile('graph.dot');
Hook into Artisan Create a custom Artisan command to wrap the graph generation with additional logic:
php artisan make:command CheckDependencies
// app/Console/Commands/CheckDependencies.php
public function handle() {
$graph = new \Spatie\TypeGraph\TypeGraph('type-graph.json');
if ($graph->hasDependency('App\Services\Payment', 'App\Legacy\PaymentGateway')) {
$this->error('Forbidden dependency detected!');
}
}
Visualization Tools Use the graph data to generate visual diagrams with tools like Mermaid or D3.js. Example Mermaid snippet:
graph TD
A[App\Models\User] --> B[App\Contracts\Authenticatable]
A --> C[Illuminate\Database\Eloquent\Model]
How can I help you explore Laravel packages today?