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 Strict Rules Laravel Package

kcs/phpstan-strict-rules

Fork of thecodingmachine/phpstan-strict-rules to support PHPStan v2. Adds stricter best-practice rules beyond core PHPStan, especially around exception handling (avoid throwing base Exception, empty catches, proper rethrowing).

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps

  1. Install the package via Composer:

    composer require --dev kcs/phpstan-strict-rules
    
  2. Enable via phpstan/extension-installer (recommended):

    composer require --dev phpstan/extension-installer
    

    This auto-configures the package in your phpstan.neon.

  3. First use case: Run PHPStan on a Laravel controller to catch superglobal usage or exception anti-patterns:

    vendor/bin/phpstan analyse app/Http/Controllers
    

Where to Look First

  • Rules list: README.md#rules-list to understand scope.
  • Configuration: vendor/kcs/phpstan-strict-rules/phpstan-strict-rules.neon for rule details.
  • Laravel-specific quirks: Check if rules conflict with Eloquent models or facades (e.g., Route:: superglobals).

Implementation Patterns

Usage Patterns

1. Exception Handling Workflow

  • Before: Throwing raw Exception or empty catch blocks.
    try {
        $user = User::findOrFail($id);
    } catch (Exception $e) {} // Empty catch → violation
    
  • After: Subtyped exceptions and proper chaining.
    try {
        $user = User::findOrFail($id);
    } catch (ModelNotFoundException $e) {
        throw new ValidationException("User not found.", 0, $e);
    }
    

2. Superglobal Replacement

  • Before: Direct $_GET usage in Laravel.
    $id = $_GET['id']; // Forbidden
    
  • After: Use Laravel’s Request object.
    use Illuminate\Http\Request;
    $id = request()->input('id'); // Allowed
    
  • Exception: Root-level index.php usage is tolerated (e.g., PSR-7 initialization).

3. Switch Statement Safety

  • Before: Missing default case.
    switch ($status) {
        case 'active': return true;
        case 'inactive': return false;
        // No default → violation
    }
    
  • After: Explicit default with exception.
    switch ($status) {
        case 'active': return true;
        case 'inactive': return false;
        default: throw new InvalidArgumentException("Unknown status: $status");
    }
    

Workflows

Daily Development

  1. Run PHPStan in CI:
    # .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
    
  2. Fix violations incrementally:
    • Use --error-format=github for PR feedback.
    • Exclude legacy paths in phpstan.neon:
      paths:
          exclude:
              - app/OldCode/**
      

Laravel-Specific Integration

  • Disable conflicting rules for Eloquent or facades:
    rules:
        TheCodingMachine\StrictRules\Rules\NoPublicPropertiesRule:
            excludeClasses:
                - App\Models\User
    
  • Pair with phpstan/laravel:
    composer require --dev phpstan/laravel
    

Tips for Laravel Projects

  • Facade superglobals: Rules may flag Route::, Cache::, etc. Exclude them:
    rules:
        TheCodingMachine\StrictRules\Rules\ForbiddenSuperglobalsRule:
            allowedFunctions:
                - Route::*
                - Cache::*
    
  • Test coverage: Run PHPStan on migrations, console commands, and service providers (not just controllers).

Gotchas and Tips

Pitfalls

  1. False Positives in Laravel:

    • Eloquent models: public properties (e.g., $fillable) may violate NoPublicPropertiesRule. Exclude them:
      rules:
          TheCodingMachine\StrictRules\Rules\NoPublicPropertiesRule:
              excludeClasses:
                  - App\Models\*
      
    • Facades: Route::, Auth::, etc., are technically superglobals. Whitelist them (see above).
  2. Performance Overhead:

    • Running --level=max with all rules may slow down CI. Start with:
      vendor/bin/phpstan analyse --level=5
      
  3. Root-Level Superglobals:

    • The package allows $_GET/$_POST in index.php (e.g., for PSR-7 initialization). Avoid using them elsewhere.
  4. Exception Chaining:

    • The rule requiring previous exceptions in catch blocks may break legacy code:
      catch (Exception $e) {
          throw new RuntimeException("Failed.", 0, $e); // Required
      }
      

Debugging

  • Isolate violations: Run PHPStan on a single file to debug:
    vendor/bin/phpstan analyse app/Http/Controllers/UserController.php
    
  • Check rule IDs: Use --error-format=json to identify rule names:
    vendor/bin/phpstan analyse --error-format=json | jq '.files[].messages[] | {rule,message}'
    
    Example output:
    {
      "rule": "TheCodingMachine\\StrictRules\\Rules\\ForbiddenSuperglobalsRule",
      "message": "Superglobal $_GET is forbidden."
    }
    

Extension Points

  1. Customize Rules:

    • Override phpstan-strict-rules.neon in your project:
      includes:
          - vendor/kcs/phpstan-strict-rules/phpstan-strict-rules.neon
          - phpstan-custom-rules.neon
      
    • Example: Disable NoPublicPropertiesRule for specific classes.
  2. Add New Rules:

    • Extend PHPStan’s Rule class and include in your config:
      services:
          - TheCodingMachine\StrictRules\Rules\CustomRule
      
  3. Gradual Adoption:

    • Use level to enable rules incrementally:
      level: 3 # Start with basic rules
      
    • Later, increase to max or enable specific rules:
      rules:
          TheCodingMachine\StrictRules\Rules\ExceptionSubtypingRule: true
      

Laravel-Specific Quirks

  • Service Providers: Avoid global variables (e.g., $app['config']). Use dependency injection:
    // Before (violation)
    $config = $app['config'];
    
    // After
    public function __construct(protected Config $config) {}
    
  • Migrations: Superglobals like $_ENV may be flagged. Use Laravel’s env() helper instead.

Pro Tips

  1. Pair with pint:

    composer require --dev laravel/pint
    vendor/bin/pint --test
    

    Enforce consistent code style alongside static analysis.

  2. CI Feedback:

    • Use phpstan/phpstan-github-action for GitHub PR annotations:
      - uses: phpstan/phpstan-github-action@v1
        with:
          level: max
      
  3. Document Exceptions:

    • Add comments for excluded rules:
      // phpcs:ignore TheCodingMachine.StrictRules.NoPublicPropertiesRule
      public $fillable = ['name', 'email'];
      
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.
codifyo/ts-generator-bundle
andydefer/laravel-cluster
testo/fiber
mintobit/jobqueue
a4sex/maintenance-bundle
a4sex/entity-date-update
a4sex/client-identifier
a4sex/base-utilites
a4sex/key-value-storage
a4sex/micro-status
chilldev/dependency-injection-extra
datinglibre/datinglibre-app-api
biberltd/corebundle
bricre/symfony-bundle-test
biberltd/logbundle
dominium/http-adapter-bundle
dominium/google-analytics
a4sex/auto-clean-entity
christhompsontldr/laravel-inky
spatie/mailcoach-vapor