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

Dead Code Detector Laravel Package

shipmonk/dead-code-detector

PHPStan extension that detects and helps remove unused PHP code. Finds dead methods/properties/constants/enum cases, dead cycles and transitive dead members, even dead tested code. Supports popular frameworks like Symfony and is configurable via usage providers.

View on GitHub
Deep Wiki
Context7

Technical Evaluation

Architecture Fit

  • Laravel Compatibility: Remains a near-perfect fit for Laravel, with explicit support for Laravel-specific patterns (routes, Eloquent, events, jobs, etc.). The package continues to leverage PHPStan’s static analysis engine, which is already a standard tool in modern PHP/Laravel ecosystems. The new fix for array_column() string keys (#362) improves accuracy for dynamic array access patterns, which are common in Laravel (e.g., collection manipulation, API responses).
  • Integration with Existing Tooling: Seamlessly integrates with PHPStan, requiring no additional infrastructure. The new release does not introduce new dependencies or runtime overhead.
  • Non-Invasive: Operates as a static analysis tool with zero runtime impact, making it ideal for CI/CD pipelines or local development workflows.

Integration Feasibility

  • Low Barrier to Entry: Installation and configuration remain unchanged:
    1. PHPStan (composer require --dev phpstan/phpstan).
    2. Package (composer require --dev shipmonk/dead-code-detector).
    3. Minimal phpstan.neon setup.
  • Laravel-Specific Features: Automatically detects Laravel patterns (e.g., #[AsEventListener] annotations, route callbacks) without manual configuration. The fix for #[AsEventListener] (#356) and the new array_column() fix (#362) further reduce false negatives for dynamic Laravel code.
  • Test Coverage: Continues to support excluding test-only usages, critical for Laravel projects where test code often references production classes.

Technical Risk

  • False Positives/Negatives:
    • Mitigated by fixes: The resolution for #[AsEventListener] (#356) and array_column() (#362) reduces false negatives for Symfony/Laravel event listeners and dynamic array access. However, complex dynamic calls (e.g., app()->make() or data_get()) may still require custom MemberUsageProvider configurations.
    • Transitive dead code: The package’s "dead cycle" detection helps, but manual review may still be needed for intricate dependency chains.
  • Performance Overhead:
    • PHPStan analysis remains CPU-intensive for large codebases. Mitigations:
      • Incremental CI runs (e.g., --generate-baseline).
      • Memory limits (--memory-limit).
  • Breaking Changes:
    • Low risk: The release is fix-only (no new features or breaking changes). However, future PHPStan major versions could introduce compatibility issues.
    • Automatic removal: The --error-format removeDeadCode flag remains destructive; use cautiously (e.g., in a branch).

Key Questions

  1. Scope of Analysis:
    • Should analysis focus on only src/ (excluding tests) or the entire codebase (including tests)?
    • How will third-party library usage (e.g., $this->someService->method() or array_column()) be handled to avoid false positives?
  2. CI/CD Integration:
    • Should dead code detection block merges (fail CI) or run as a warning-only check?
    • How will automatic removal be tested/safeguarded (e.g., via PR previews)?
  3. Customization Needs:
    • Are there Laravel-specific patterns (e.g., dynamic route generation, macro methods, or array_column() usage) not covered by default providers?
    • Will custom MemberUsageProvider/MemberUsageExcluder implementations be required for edge cases (e.g., legacy dynamic array access)?
  4. Maintenance:
    • Who will review and approve dead code removals (e.g., via GitHub PRs)?
    • How will false positives (e.g., array_column() misclassifications) be documented and excluded (e.g., via phpstan.neon)?
  5. Tooling Stack:
    • Is PHPStan already used in the team? If not, what’s the ramp-up cost for adoption?
    • Will the package integrate with existing linters (e.g., PSalm, Pest) or IDE plugins (e.g., PHPStorm inspections)?

Integration Approach

Stack Fit

  • PHPStan Integration: The package remains a PHPStan extension, fitting naturally into stacks using:
    • PHPStan for static analysis.
    • Laravel’s dependency injection (for service usage detection).
    • Composer for dev-dependency management.
  • Laravel-Specific Support: Out-of-the-box detection for:
    • Routing (e.g., Route::get(fn() => ...)).
    • Eloquent (e.g., model observers, query scopes).
    • Events/Jobs: Improved with fixes for #[AsEventListener] (#356).
    • Dynamic Arrays: New fix for array_column() (#362) reduces false positives in collection/response handling.
    • Testing (e.g., PHPUnit data providers, Behat steps).
  • Tooling Compatibility:
    • Works with GitHub Actions, GitLab CI, or local dev environments.
    • Compatible with Pest (via PHPUnit support) and Laravel Forge for deployment checks.

Migration Path

  1. Phase 1: Static Analysis (Non-Destructive)

    • Install PHPStan and the package:
      composer require --dev phpstan/phpstan shipmonk/dead-code-detector
      
    • Configure phpstan.neon:
      includes:
          - vendor/shipmonk/dead-code-detector/rules.neon
      parameters:
          shipmonkDeadCode:
              usageExcluders:
                  tests:
                      enabled: true
                  # Add exclusion for array_column if needed
                  array_column:
                      enabled: true
                      patterns:
                          - "array_column($responseData, 'key')"
      
    • Run analysis:
      vendor/bin/phpstan analyse --level=max
      
    • Review output for false positives/negatives. Document exclusions in phpstan.neon.
  2. Phase 2: CI/CD Enforcement

    • Add a CI step (e.g., GitHub Actions):
      - name: Dead Code Detection
        run: vendor/bin/phpstan analyse --error-format=github
      
    • Configure to fail on warnings (or errors, depending on team preference).
  3. Phase 3: Automated Removal (Optional)

    • Test automatic removal in a branch:
      vendor/bin/phpstan analyse --error-format=removeDeadCode --generate-migration
      
    • Review generated diffs, then apply in a PR.
    • Safeguard: Require manual approval for removal PRs.

Compatibility

  • Laravel Versions: Supports modern Laravel (8+) with Symfony 6+/PHP 8.1+.
  • PHPStan Versions: Requires PHPStan 1.x (check release notes for compatibility).
  • IDE Support: Works with PHPStorm’s PHPStan plugin for real-time dead code highlighting.
  • Test Frameworks: Supports PHPUnit, Pest, PhpBench, and Behat (no conflicts).

Sequencing

  1. Pilot on a Subset:
    • Start with a single module (e.g., app/Http/Controllers) to validate findings.
  2. Gradual Expansion:
    • Add app/Models, app/Console, etc., over time.
  3. Customization:
    • Implement MemberUsageProvider for edge cases (e.g., dynamic method calls or array_column() misclassifications).
  4. Automation:
    • Integrate with PR checks (e.g., "This PR introduces dead code").
    • Schedule weekly dead code cleanup sprints.

Operational Impact

Maintenance

  • Configuration Drift:
    • Risk: phpstan.neon may grow complex with exclusions/providers, especially with the new array_column() fix.
    • Mitigation:
      • Use comments to document why exclusions exist.
      • Store custom providers in a dedicated config/phpstan/ directory.
      • Example exclusion for array_column:
        parameters:
            shipmonkDeadCode:
                usageExcluders:
                    custom:
                        enabled: true
                        patterns:
                            - "array_column($this->data, 'status')"
        
  • False Positives:
    • Risk: New Laravel features or custom logic (e.g., array_column()) may break detection.
    • Mitigation:
      • Test new code with the tool enabled.
      • Maintain a list of known exclusions (e.g., in a DEAD_CODE_EXCEPTIONS.md file).
      • Document the array_column() fix in the team’s runbook.
  • Dependency Updates:
    • Risk: PHPStan or the package may introduce breaking changes.
    • Mitigation:
      • Pin versions in `composer.json
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.
jayeshmepani/jpl-moshier-ephemeris-php
elnasnato/laraliveui
labrodev/rest-sdk
sampaui/sampaui
babelqueue/php-sdk
facebook/capi-param-builder-php
babelqueue/symfony
hamzi/corewatch
minionfactory/raw-hydrator
hexters/coinpayment
rjcodes/rjcms
act-training/laravel-permissions-manager
alimarchal/laravel-chart-of-accounts
babenkoivan/elastic-scout-driver
mkwebdesign/filament-watchdog-v5
renatomarinho/laravel-page-speed
zedmagdy/filament-business-hours
renatovdemoura/blade-elements-ui
devgeek/beacon-admin
benjamin-rqt/data-watcher-bundle