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 that flags banned code patterns in your project (e.g., var_dump, dd, exit/die, eval, echo/print, shell exec/backticks). Configurable via PHPStan parameters, with optional checks like preventing use imports from Tests in non-test code.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Install via Composer (dev dependency):

    composer require --dev ekino/phpstan-banned-code
    
  2. Enable via Extension Installer (recommended):

    composer require --dev phpstan/extension-installer
    

    This auto-includes the extension in your PHPStan config.

  3. Manual Configuration (if not using installer): Add to your phpstan.neon:

    includes:
        - vendor/ekino/phpstan-banned-code/extension.neon
    

First Use Case: Block Debug Functions

Run PHPStan with default rules to catch var_dump, dd(), exit(), etc.:

./vendor/bin/phpstan analyse app

Example output:

[ERROR]  app/Http/Controllers/ProductController.php:12:10 - Banned function call: var_dump()

Implementation Patterns

1. Team-Wide Debug Prevention

Workflow:

  • Configure banned_code.nodes in phpstan.neon to block debug functions:
    parameters:
        banned_code:
            nodes:
                - type: Expr_FuncCall
                  functions:
                      - dd
                      - dump
                      - var_dump
                      - print_r
    
  • CI Integration: Add to GitHub Actions/GitLab CI:
    - name: Run PHPStan with banned-code rules
      run: ./vendor/bin/phpstan analyse --level=max --error-format=github
    

2. Security Hardening

Pattern: Ban shell execution and eval:

parameters:
    banned_code:
        nodes:
            - type: Expr_FuncCall
              functions:
                  - exec
                  - shell_exec
                  - system
                  - passthru
                  - eval
            - type: Expr_ShellExec  # Backticks: ``

Laravel-Specific: Extend to block Artisan::call() in non-cli contexts:

- type: Expr_MethodCall
  functions:
      - Artisan::call

3. Legacy Code Migration

Use Case: Remove PHP 7.x deprecated functions (e.g., mysql_*):

parameters:
    banned_code:
        nodes:
            - type: Expr_FuncCall
              functions:
                  - mysql_connect
                  - mysql_query
                  - create_function
                  - call_user_func_array

Tip: Use --generate-baseline to exclude legacy files temporarily.

4. Test-Specific Rules

Pattern: Block use Tests\* in non-test files:

parameters:
    banned_code:
        use_from_tests: true

Laravel Example: Prevent test helpers in controllers:

- type: Stmt_Use
  functions:
      - Tests\Helpers\TestHelper

5. Custom Rule Extension

Example: Ban Log::debug() in production:

parameters:
    banned_code:
        nodes:
            - type: Expr_MethodCall
              functions:
                  - Log::debug
              # Optional: Restrict to specific classes
              classes:
                  - App\Services\Logger

Gotchas and Tips

Pitfalls

  1. False Positives in Generators:

    • The rule may flag yield or yield from as "banned" if misconfigured.
    • Fix: Exclude generator-related nodes by adjusting type in config.
  2. Closure Scope Issues:

    • Anonymous functions with use statements may trigger use_from_tests rules.
    • Fix: Temporarily disable use_from_tests or whitelist closures:
      parameters:
          banned_code:
              use_from_tests: false
      
  3. Non-Ignorable Errors:

    • Errors are non-ignorable by default (cannot be added to baseline).
    • Workaround: Set non_ignorable: false if you need to baseline exceptions.
  4. Performance Overhead:

    • Large codebases may slow down analysis due to AST traversal.
    • Tip: Run in CI with --parallel or exclude directories:
      phpstan analyse --exclude vendor,storage
      

Debugging Tips

  1. Verbose Output: Use --debug to see which nodes are being analyzed:

    ./vendor/bin/phpstan analyse --debug
    
  2. Isolate Rules: Test one rule at a time by commenting out sections in phpstan.neon.

  3. Baseline Management:

    • Use --generate-baseline to exclude known violations:
      phpstan analyse --generate-baseline
      
    • Warning: Only use this for temporary exclusions (e.g., legacy code).
  4. Custom Node Types:

    • Check PHPStan’s AST documentation to map custom node types (e.g., Expr_StaticCall for ::method()).

Extension Points

  1. Add Custom Functions: Extend the functions list in Expr_FuncCall for project-specific bans:

    - type: Expr_FuncCall
      functions:
          - App\Helpers\Debug::log
    
  2. Whitelist Directories: Use PHPStan’s paths to exclude directories (e.g., tests):

    paths:
        - app
        - src
    
  3. Dynamic Configuration: Load banned functions from a .env file or config:

    // config/phpstan.php
    return [
        'banned_functions' => explode(',', env('BANNED_FUNCTIONS', 'dd,dump,var_dump')),
    ];
    

    Then reference in phpstan.neon:

    parameters:
        banned_code:
            nodes:
                - type: Expr_FuncCall
                  functions: %banned_functions%
    

Laravel-Specific Quirks

  1. Facade Calls: Ban Laravel facades (e.g., Log::debug) by targeting Expr_StaticCall:

    - type: Expr_StaticCall
      functions:
          - Log::debug
          - Cache::put
    
  2. Blade Debugging: Detect {{ dd($var) }} by analyzing Blade templates (requires custom rule extension).

  3. Service Container: Block app()->bind() or app()->singleton() in non-bootstrap files:

    - type: Expr_MethodCall
      functions:
          - Illuminate\Container\Container::bind
    

Pro Tips

  • Combine with PHP-CS-Fixer: Use php-cs-fixer to auto-fix echo/print statements, then ban them with this package.
  • Git Hooks: Add a pre-commit hook to run PHPStan with banned-code rules locally:
    # .git/hooks/pre-commit
    ./vendor/bin/phpstan analyse --memory-limit=512M
    
  • Visual Studio Code: Integrate with the PHPStan extension for real-time feedback.
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