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

shipmonk/phpstan-rules

40 super-strict PHPStan rules from ShipMonk to close gaps even in extra-strict setups. Installs as an extension, configurable per rule (enable/disable, tweak defaults), with options like safer comparisons, enum generics checks, and more.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:
    composer require --dev shipmonk/phpstan-rules
    
  2. Enable Rules in phpstan.neon:
    includes:
        - vendor/shipmonk/phpstan-rules/rules.neon
    
  3. Run PHPStan:
    vendor/bin/phpstan analyse
    

First Use Case

Start with forbidCast and forbidArithmeticOperationOnNonNumber—these catch common type-safety issues early. Example:

// Fails: forbidden cast
$arr = (array) null;

// Fails: arithmetic on non-number
$str = "10";
$str + 5; // Error

Implementation Patterns

Workflow Integration

  1. Incremental Adoption:

    • Enable enforceNativeReturnTypehint and enforceClosureParamNativeTypehint first to modernize type hints.
    • Gradually add stricter rules like enforceReadonlyPublicProperty (PHP 8.1+) or forbidCheckedExceptionInCallable (for exception safety).
  2. Team Onboarding:

    • Use classSuffixNaming to enforce naming conventions (e.g., *Test for tests).
    • Configure forbidCustomFunctions to block legacy patterns (e.g., call_user_func_array).
  3. Legacy Code:

    • Disable rules selectively via ! in config:
      parameters:
          shipmonkRules:
              forbidCast:
                  blacklist!: ['(array)'] # Only block (array) casts
      

Common Patterns

  • Enum Handling: Use enforceEnumMatch to replace verbose if-else chains with match expressions:

    // Before (error-prone)
    if ($status === Status::PENDING) { ... }
    
    // After (recommended)
    return match ($status) {
        Status::PENDING => 'pending',
        Status::APPROVED => 'approved',
    };
    
  • Immutable Properties: Enforce readonly with enforceReadonlyPublicProperty (PHP 8.1+):

    class User {
        public readonly string $name; // Enforced
        public string $email; // Fails
    }
    
  • Iterator Safety: Require explicit iterator_to_array($iterator, false) with enforceIteratorToArrayPreserveKeys to avoid silent key collisions.


Gotchas and Tips

Pitfalls

  1. BackedEnum Generics:

    • backedEnumGenerics requires a custom stub file (see ShipMonk’s guide).
    • Fix: Add to phpstan.neon:
      parameters:
          stubFiles:
              - vendor/shipmonk/phpstan-rules/BackedEnum.php.stub
      
  2. False Positives:

    • forbidCheckedExceptionInCallable may flag Symfony’s Question::setValidator (allow via config):
      parameters:
          shipmonkRules:
              forbidCheckedExceptionInCallable:
                  allowedCheckedExceptionCallables:
                      'Symfony\Component\Console\Question::setValidator': 0
      
  3. PHP Version Limits:

    • Rules like enforceReadonlyPublicProperty or enforceNativeReturnTypehint require PHP 8.1+. Use ignoreErrors to bypass:
      ignoreErrors:
          - '#^Cannot use readonly property on PHP < 8.1$#'
      

Debugging Tips

  • Rule-Specific Config: Override defaults with ! to avoid merging:

    parameters:
        shipmonkRules:
            forbidCast:
                blacklist!: ['(array)'] # Overrides all defaults
    
  • Selective Enforcement: Disable all rules first, then enable only needed ones:

    parameters:
        shipmonkRules:
            enableAllRules: false
            enforceNativeReturnTypehint:
                enabled: true
    

Extension Points

  1. Custom Rules: Extend the package by adding new rules to rules.neon:

    includes:
        - vendor/shipmonk/phpstan-rules/rules.neon
        - path/to/custom-rules.neon
    
  2. CI Integration: Use PHPStan’s --error-format=json to parse results in CI:

    vendor/bin/phpstan analyse --error-format=json | jq '.files[] | select(.errors | length > 0)'
    
  3. Performance: Exclude tests or large directories:

    paths:
        - src/
        - tests/ # Excluded
    
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
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
twbs/bootstrap4