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

Technical Evaluation

Architecture Fit

  • Pros:
    • Defensive Programming Alignment: Rules like exception subtyping, default switch cases, and superglobal restrictions directly support Laravel’s emphasis on robustness and security.
    • Framework Agnostic but Laravel-Friendly: While framework-agnostic, the rules (e.g., avoiding superglobals) align with Laravel’s PSR-7 request handling and dependency injection principles.
    • Low Invasive: Operates as a PHPStan extension, requiring no core Laravel modifications. Integrates seamlessly with existing static analysis workflows.
  • Cons:
    • Potential Conflicts with Laravel Patterns:
      • Eloquent Models: Rules like "no public properties" may clash with Laravel’s dynamic properties (e.g., with() macros) or legacy model visibility.
      • Service Providers/Bootstrap: Superglobal restrictions could flag Laravel’s index.php or bootstrap/app.php (though root-scope exemptions mitigate this).
      • Magic Methods: Rules targeting property visibility might interfere with Laravel’s __get()/__set() magic.
    • Opinionated Strictness: Some rules (e.g., forbidding globals) may be overkill for Laravel’s config files or service container bindings.

Integration Feasibility

  • High:
    • PHPStan v2 Compatibility: Native support in Laravel via phpstan/extension-installer or manual phpstan.neon configuration.
    • Zero Laravel-Specific Dependencies: Pure PHPStan extension; no Laravel core or package modifications required.
    • Gradual Adoption: Rules can be enabled selectively (e.g., by file path, namespace, or --level) to avoid breaking changes.
  • Compatibility:
    • Works alongside phpstan/laravel for framework-specific rules.
    • No conflicts with Laravel’s Pint, CS Fixer, or IDE plugins (e.g., PHPStorm’s PHPStan integration).
  • Testing:
    • Isolated Validation: Test rules against a subset of code (e.g., new features) before full rollout.
    • CI/CD Dry Runs: Use --generate-baseline to baseline existing code and phase in rules incrementally.

Technical Risk

  • Low-Medium:
    • False Positives:
      • Superglobal Rule: May flag Laravel’s facades (e.g., Route::input()) or legacy bootstrap code.
      • Exception Rules: Could misfire on Laravel’s custom exception handling (e.g., throw new HttpResponseException).
    • Performance:
      • Additional rules may increase PHPStan analysis time by 10–30% (mitigated by CI parallelization or selective enabling).
    • Maintenance:
      • Fork Dependency: Long-term viability hinges on the fork’s adoption or upstream revival. Monitor for abandonment risks.
      • Rule Updates: If TheCodingMachine revives their original repo, this fork may become stale.
    • Developer Friction:
      • Strict rules (e.g., no public properties) may require refactoring (e.g., converting Eloquent models to use protected properties).

Key Questions

  1. Rule Conflict Resolution:
    • How to exclude specific Laravel patterns (e.g., facades, Eloquent) from rules like ForbiddenSuperglobalsRule or NoPublicPropertiesRule?
    • Example: Should app/Http/Controllers/ be exempt from superglobal checks?
  2. Adoption Strategy:
    • Phased Rollout: Start with non-breaking rules (e.g., exception handling) before enforcing stricter ones (e.g., property visibility).
    • Legacy Code: How to handle existing violations (e.g., superglobals in routes/web.php)? Options:
      • Gradual fixes via deprecation warnings.
      • Opt-in enforcement for new code only.
  3. Tooling Integration:
    • Can this integrate with Laravel’s pint or PHP-CS-Fixer for unified formatting + static analysis?
    • Should it replace or complement existing tools like roave/security-advisories?
  4. Performance Impact:
    • Benchmark CI/CD runtime with/without this package. Target <5% increase in build time.
    • Optimize by disabling rules for excluded paths (e.g., node_modules, vendor).
  5. Fork Governance:
    • Monitor the original repo’s activity. If revived, decide whether to:
      • Switch to the original package.
      • Maintain this fork as a long-term alternative.
    • Contribute upstream to ensure rule compatibility with Laravel’s evolving patterns.
  6. Developer Experience:
    • How to educate the team on rule justifications (e.g., why public properties are banned)?
    • Provide actionable feedback in PRs (e.g., "Fix this by using protected or a getter").

Integration Approach

Stack Fit

  • PHPStan Ecosystem:
    • Primary Use Case: Extends Laravel’s static analysis with TheCodingMachine’s best practices.
    • Synergies:
      • phpstan/laravel: Combine with Laravel-specific rules for comprehensive coverage.
      • phpstan/phpunit: Enforce testing best practices alongside code quality.
      • phpstan/extension-installer: Zero-config integration via Composer.
    • Alternatives:
      • vimeo/psalm: If team prefers Psalm over PHPStan.
      • Custom Rules: For domain-specific logic beyond this package’s scope.
  • Laravel-Specific Considerations:
    • Superglobal Rule: Conflicts with Laravel’s facades (e.g., request()->input()). Mitigate by:
      • Excluding app/Http/ from superglobal checks.
      • Using phpstan.neon overrides:
        rules:
            TheCodingMachine\StrictRules\Rules\ForbiddenSuperglobalsRule:
                excludeFiles: ['app/Http/**', 'routes/**']
        
    • Exception Rules: Aligns with Laravel’s custom exception handling (e.g., throw new \App\Exceptions\Handler).
    • Property Rules: May require Eloquent model adjustments (e.g., using protected instead of public).

Migration Path

  1. Preparation:

    • Audit Current Setup:
      • Verify PHPStan version (>=1.10.0 for PHPStan v2 support).
      • Check for existing phpstan.neon configurations.
    • Baseline Code:
      vendor/bin/phpstan analyse --generate-baseline
      
    • Document Exceptions: Identify Laravel-specific patterns that may violate rules (e.g., facades, Eloquent).
  2. Pilot Phase:

    • Install Package:
      composer require --dev kcs/phpstan-strict-rules
      
    • Enable Selectively:
      # phpstan.neon
      includes:
          - vendor/kcs/phpstan-strict-rules/phpstan-strict-rules.neon
      level: max
      rules:
          TheCodingMachine\StrictRules\Rules\:
              - "ExceptionSubtypingRule"       # Enable first (low impact)
              - "NoEmptyCatchRule"            # Enable next
              - "ForbiddenSuperglobalsRule"   # Exclude paths: see below
              - "DefaultCaseInSwitchRule"     # Enable last
      paths:
          exclude:
              - "app/Http/**"                 # Exempt facades
              - "routes/**"                  # Exempt legacy superglobals
      
    • Test Locally:
      • Run on a subset of code (e.g., new feature branch).
      • Validate false positives and adjust exclusions.
  3. Gradual Rollout:

    • Phase 1: Enable exception-related rules (low risk).
    • Phase 2: Add superglobal restrictions (exclude app/Http/, routes/).
    • Phase 3: Introduce property/condition rules (e.g., NoPublicPropertiesRule).
    • CI/CD Integration:
      • Add to GitHub Actions or Laravel Forge:
        # .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 --error-format=github
        
  4. Post-Rollout:

    • Monitor False Positives: Track and adjust exclusions.
    • Educate Team: Share rule rationales (e.g., why public properties are discouraged).
    • Iterate: Revisit exclusions as Laravel patterns evolve.

Compatibility

  • Laravel Versions: Compatible with Laravel 8+ (PHP 7.4+ required).
  • PHPStan Versions: Requires PHPStan v1.10.0+ (for PHPStan v
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