Weave Code
Code Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Php Type Graph Laravel Package

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).

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps

  1. 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.

  2. 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');
    

Where to Look First

  • Generated Output: Check type-graph.json for the full dependency graph.
  • CLI Commands: Run php artisan type-graph:generate --help to explore options like --exclude or --output.
  • Documentation: Review the README for advanced usage (e.g., filtering by namespace).

Implementation Patterns

Usage Patterns

  1. 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.
    
  2. 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'));
    }
    
  3. 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
    

Workflows

  • 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.
    

Integration Tips

  • 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.
        }
    }
    

Gotchas and Tips

Pitfalls

  1. 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/*"
    
  2. 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');
    
  3. Outdated Graphs Always regenerate the graph before critical checks, as it reflects the state of the codebase at generation time.

Debugging

  • 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).

Config Quirks

  • 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\\"
    

Extension Points

  1. Custom Graph Formatters Extend the package to output the graph in alternative formats (e.g., DOT for Graphviz):

    $graph->toDot()->saveToFile('graph.dot');
    
  2. 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!');
        }
    }
    
  3. 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]
    
Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
davejamesmiller/laravel-breadcrumbs
artisanry/parsedown
christhompsontldr/phpsdk
enqueue/dsn
bunny/bunny
enqueue/test
enqueue/null
enqueue/amqp-tools
milesj/emojibase
bower-asset/punycode
bower-asset/inputmask
bower-asset/jquery
bower-asset/yii2-pjax
laravel/nova
spatie/laravel-mailcoach
spatie/laravel-superseeder
laravel/liferaft
nst/json-test-suite
danielmiessler/sec-lists
jackalope/jackalope-transport