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

Phpstan Banned Code Laravel Package

ekino/phpstan-banned-code

PHPStan extension to ban unwanted code in your project. Detects calls like var_dump, dd, eval, exit/die, echo/print, shell exec/backticks, and even “use” imports from Tests in non-test files. Configurable rules for CI enforcement.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Install the package in your Laravel project:
    composer require --dev ekino/phpstan-banned-code
    
  2. Enable the extension via one of these methods:
    • Recommended: Use PHPStan extension-installer (auto-configures on install).
    • Manual: Add to your phpstan.neon:
      includes:
          - vendor/ekino/phpstan-banned-code/extension.neon
      
  3. Run PHPStan to detect banned code:
    vendor/bin/phpstan analyse app --level=max
    

First Use Case: Block Debug Functions

Configure phpstan.neon to ban dd(), var_dump, and exit():

parameters:
    banned_code:
        nodes:
            - type: Expr_FuncCall
              functions: [dd, var_dump, dump]
            - type: Expr_Exit
              functions: null

Expected Output: PHPStan errors for any banned function calls, e.g.:

Banned function call: dd($user)

Implementation Patterns

1. Team-Wide Enforcement in CI

Add to .github/workflows/phpstan.yml:

jobs:
  phpstan:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - run: composer install
      - run: vendor/bin/phpstan analyse --level=max

Pattern: Fail builds on banned code by default (use non_ignorable: true in config).

2. Project-Specific Bans

Customize extension.neon for Laravel conventions:

parameters:
    banned_code:
        nodes:
            # Laravel-specific
            - type: Expr_FuncCall
              functions: [dd, dump, artisan, tinker]
            # Security risks
            - type: Expr_FuncCall
              functions: [exec, shell_exec, passthru, system]
            # Deprecated PHP
            - type: Expr_FuncCall
              functions: [mysql_connect, create_function]
            # Performance
            - type: Stmt_Echo
              functions: null

Tip: Use type: Expr_FuncCall for functions, type: Stmt_Echo for statements.

3. Excluding Tests

Allow dd() in test files but ban in production:

parameters:
    banned_code:
        use_from_tests: true  # Allows test-specific uses
        nodes:
            - type: Expr_FuncCall
              functions: [dd]
              exclude_namespaces: ['Tests\\']

Pattern: Combine use_from_tests with exclude_namespaces for granular control.

4. Integration with Laravel Debug Mode

Use PHPStan’s level to enforce bans only in production-like environments:

# CI/CD (strict)
vendor/bin/phpstan analyse --level=max

# Local dev (relaxed)
vendor/bin/phpstan analyse --level=5

5. Dynamic Bans via Environment

Load banned functions from .env:

parameters:
    banned_code:
        nodes:
            - type: Expr_FuncCall
              functions: %env(BANNED_FUNCTIONS)%  # e.g., "dd,var_dump,exec"

Example .env:

BANNED_FUNCTIONS="dd,var_dump,exec,shell_exec"

6. Legacy Code Migration

Phase out deprecated functions incrementally:

parameters:
    banned_code:
        nodes:
            - type: Expr_FuncCall
              functions: [mysql_connect, mysql_query]  # Phase 1
              # - type: Expr_FuncCall       # Uncomment after migration
              #   functions: [create_function]  # Phase 2

Gotchas and Tips

Pitfalls

  1. False Positives in Closures

    • Issue: Bans may trigger in closures (e.g., array_map('dd', $items)).
    • Fix: Use exclude_namespaces or adjust extension.neon to target only named functions.
  2. Non-Ignorable Errors

    • Issue: Errors are non-ignorable by default (non_ignorable: true), blocking baseline updates.
    • Fix: Set non_ignorable: false if you need to ignore specific instances temporarily.
  3. Case Sensitivity

    • Issue: VarDump (camelCase) won’t match var_dump (snake_case).
    • Fix: Normalize function names in the config (e.g., always use snake_case).
  4. Backtick Shell Execution

    • Issue: shell_exec via backticks (echo id``) may bypass Expr_FuncCall rules.
    • Fix: Enable Expr_ShellExec in config:
      - type: Expr_ShellExec
        functions: null
      
  5. Performance Impact

    • Issue: Overly broad rules (e.g., banning echo) can slow down analysis.
    • Fix: Target specific files/directories:
      vendor/bin/phpstan analyse app/Http --level=max
      
  6. PHPStan Version Mismatch

    • Issue: Extension may not work with PHPStan <2.x or >3.x.
    • Fix: Pin PHPStan version in composer.json:
      "require-dev": {
          "phpstan/phpstan": "^1.10 || ^2.0 || ^3.0"
      }
      

Debugging Tips

  1. Inspect AST Nodes Use PHPStan’s --debug flag to see node types:

    vendor/bin/phpstan analyse --debug
    

    Look for entries like Expr_FuncCall: var_dump.

  2. Test Config Incrementally Start with a single banned function (e.g., dd) and expand:

    parameters:
        banned_code:
            nodes:
                - type: Expr_FuncCall
                  functions: [dd]  # Test first
    
  3. Baseline Exceptions If errors are non-ignorable, use --generate-baseline to exclude specific files:

    vendor/bin/phpstan analyse --generate-baseline
    

    Then edit phpstan.baseline.neon to exclude known issues.

  4. Custom Node Types For unsupported node types (e.g., Stmt_Declare), check PHPStan’s AST docs or extend the package.

Extension Points

  1. Add Custom Rules Extend the extension by creating a custom PHPStan rule:

    use Ekino\PHPStanBannedCode\Rules\BannedNodesRule;
    
    class CustomBannedNodesRule extends BannedNodesRule {
        protected function getBannedNodes(): array {
            return [
                // Add your custom node types/functions
            ];
        }
    }
    
  2. Dynamic Configuration Load banned functions from a database or API:

    parameters:
        banned_code:
            nodes:
                - type: Expr_FuncCall
                  functions: %config(banned_functions)%  # From Laravel config
    
  3. Integration with Laravel Hook into Laravel’s bootstrapping to enforce bans:

    // app/Providers/AppServiceProvider.php
    public function boot() {
        if (app()->environment('production')) {
            $this->enforceBannedCodeRules();
        }
    }
    
  4. Visual Studio Code Integration Use the PHPStan extension to see banned code errors inline during development.

Pro Tips

  • Combine with PHP-CS-Fixer: Use php-cs-fixer to auto-fix echo/print statements while banning them with PHPStan.
  • Git Hooks: Add a pre-commit hook to run PHPStan on staged files:
    # .git/hooks/pre-commit
    #!/bin/sh
    vendor/bin/phpstan analyse --memory-limit=512M --level=max
    
  • Document Banned Functions: Add a BANNED_FUNCTIONS.md to explain why each function is restricted (e.g., security, performance).
  • Monitor False Positives: Track and reduce false positives by refining exclude_namespaces or exclude_files.
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.
babenkoivan/elastic-client
innmind/static-analysis
innmind/coding-standard
datacore/hub-sdk
alengo/sulu-http-cache-bundle
develia/commons
cuci/prototurk-sdk
cuci/prototurk-sdk-symfony
develia/geo-bundle
dreamzy/livewire-charts
touchestate-sdk/php-sdk
22h/doctrine-garbage-collection-bundle
imbo/imbo-coding-standard
visualbuilder/filament-lottie
servicioslineaonce/starter-kit
atomcoder/laravel-reorderable
irajul/filament-shadcn-theme
agtp/agtp-php
agtp/mod-php
centraldesktop/protobuf-php