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

phpstan/phpstan-strict-rules

Opinionated extra rules for PHPStan to enforce strict, strongly typed PHP. Catches loose booleans in conditions, unsafe strict parameters, useless casts, non-numeric arithmetic, variable overwrites in loops, and switch/case type mismatches for safer defensive code.

View on GitHub
Deep Wiki
Context7

Technical Evaluation

Architecture Fit

  • Static Analysis Integration: The package is a PHPStan extension, meaning it integrates seamlessly into existing static analysis pipelines (e.g., CI/CD, pre-commit hooks). It does not require architectural changes to the Laravel application itself but enhances type safety and code quality.
  • Defensive Programming Alignment: The rules enforce strict typing, immutability, and defensive practices, which align with Laravel’s evolving PHP 8.x+ features (e.g., strict types, attributes, and improved type inference). This is particularly valuable for large-scale Laravel applications where maintainability and robustness are critical.
  • Opinionated vs. Customizable: The package is opinionated by default (e.g., disallowing loose comparisons, empty(), or backticks) but allows granular disablement. This makes it ideal for teams with high coding standards but may require negotiation for teams with legacy codebases.

Integration Feasibility

  • Low Friction: Installation is Composer-based (phpstan/phpstan-strict-rules) and works with phpstan/extension-installer for zero-config setups. Manual inclusion via rules.neon is also straightforward.
  • Laravel-Specific Considerations:
    • Blade Templates: PHPStan does not analyze Blade files by default. The package’s rules (e.g., disallowedBacktick) may trigger false positives in Blade contexts (e.g., shell commands in {{ !! }} or @php). Mitigation: Exclude Blade directories from PHPStan analysis or disable conflicting rules.
    • Legacy Code: Laravel applications often include loosely typed legacy code (e.g., dynamic properties, empty() checks). The package’s strict rules may break builds initially. Mitigation: Incremental adoption (disable rules per-file or per-class) or pair with PHPStan’s baseline to track violations over time.
    • Performance Overhead: PHPStan is already a CPU-intensive tool. Adding strict rules may increase analysis time (especially for large codebases). Mitigation: Run in CI incrementally or parallelize.

Technical Risk

Risk Area Description Mitigation Strategy
False Positives Rules like disallowedLooseComparison or switchConditionsMatchingType may flag legitimate PHP idioms (e.g., if ($var == null) or switch ($type) with mixed types). Test rules against a representative code sample before full adoption. Disable selectively.
Build Breaks Strict rules (e.g., requireParentConstructorCall) may fail in legacy Laravel components (e.g., older service providers, repositories). Use // @phpstan-ignore-line for known issues or refactor incrementally.
Toolchain Conflicts Conflicts with other PHPStan extensions (e.g., phpstan/phpstan-doctrine) or custom rulesets. Audit existing PHPStan config for overlaps; test integration early.
Maintenance Burden Strict rules may prohibit patterns that are hard to replace (e.g., empty() in validation logic). Document exceptions; phase out violations over time.

Key Questions for the TPM

  1. Adoption Strategy:
    • Should we enable all rules at once (risking massive refactoring) or roll out incrementally (e.g., disable allRules and enable rules by category)?
    • How will we handle false positives in legacy code? (e.g., Blade templates, third-party libraries)
  2. CI/CD Impact:
    • What is the acceptable increase in PHPStan runtime? Should we cache results or parallelize?
    • Will we block PR merges on strict rule violations, or treat them as technical debt?
  3. Team Readiness:
    • Does the team have bandwidth to refactor code to meet strict rules? If not, which rules can we disable permanently?
    • How will we educate developers on the benefits of strict rules (e.g., catching bugs early)?
  4. Long-Term Vision:
    • Does this align with our goal to modernize the Laravel codebase (e.g., stricter types, fewer dynamic calls)?
    • Should we extend PHPStan configs to include custom rules beyond this package?

Integration Approach

Stack Fit

  • PHPStan Ecosystem: The package is designed for PHPStan v1.0+, which Laravel projects using PHP 8.0+ already leverage. No additional tooling is required.
  • Laravel-Specific Tools:
    • Laravel Pint: If using Pint for code formatting, ensure it doesn’t conflict with strict rules (e.g., disallowedShortTernary may require manual fixes).
    • Pest/PhpUnit: Strict rules (e.g., noVariableVariables) may affect test readability. Mitigation: Exclude test directories or document exceptions.
  • IDE Support: Works with PHPStorm, VSCode (with Intelephense), and other IDEs that integrate with PHPStan.

Migration Path

  1. Phase 1: Assessment (1–2 weeks)
    • Install phpstan/phpstan-strict-rules in dev dependencies.
    • Run PHPStan with all rules disabled (strictRules.allRules: false) to establish a baseline.
    • Identify high-impact violations (e.g., disallowedLooseComparison in core logic vs. disallowedBacktick in Blade).
  2. Phase 2: Incremental Adoption (4–8 weeks)
    • Enable low-risk rules first (e.g., uselessCast, closureUsesThis).
    • Disable rules per-file for legacy components (e.g., // @phpstan-ignore-next-line).
    • Use PHPStan’s baseline to track progress (e.g., --generate-baseline).
  3. Phase 3: Full Enforcement (Ongoing)
    • Gradually enable stricter rules (e.g., disallowedLooseComparison, requireParentConstructorCall).
    • Deprecate code that violates rules (e.g., replace empty() with !isset() + !empty()).
    • Integrate into CI/CD with blocking checks for critical paths.

Compatibility

Component Compatibility Notes
Laravel Core Most rules are compatible, but legacy service containers (e.g., dynamic method calls) may need updates.
Blade Templates No analysis by default. Exclude from PHPStan or disable rules like disallowedBacktick.
Third-Party Packages Packages using loose comparisons (e.g., if ($var == null)) may fail. Mitigation: Patch or exclude vendor code.
PHP 8.1+ Features Rules like matchingInheritedMethodNames align with PHP 8.1’s stricter type system.
Custom Rulesets Conflicts possible with existing PHPStan configs. Mitigation: Merge configs carefully or override defaults.

Sequencing

  1. Pre-requisites:
    • Ensure PHPStan is already integrated into the project (e.g., via phpstan/extension-installer).
    • Upgrade to PHP 8.1+ (for best compatibility with strict rules).
  2. Order of Rule Enforcement:
    • Low Impact: uselessCast, numericOperandsInArithmeticOperators (quick wins).
    • Medium Impact: disallowedEmpty, disallowedShortTernary (requires logic changes).
    • High Impact: disallowedLooseComparison, requireParentConstructorCall (may break legacy code).
  3. Post-Integration:
    • Add a custom PHPStan rule to document exceptions (e.g., @phpstan-ignore-next-line usage).
    • Train developers on strict typing benefits (e.g., fewer runtime bugs).

Operational Impact

Maintenance

  • Rule Updates: The package is actively maintained (last release: 2026-05-02). New rules may introduce breaking changes in minor versions.
    • Mitigation: Pin to a specific version (e.g., ^2.0) and test upgrades.
  • Configuration Drift: Disabling rules per-file can lead to config sprawl.
    • Mitigation: Use PHPStan’s level system or a centralized config for exceptions.
  • Dependency Bloat: Adding strict rules may increase Composer lock size slightly (negligible impact).

Support

  • Developer Onboarding:
    • Pros: Reduces bugs by catching issues early (e.g., loose comparisons, dynamic calls).
    • Cons: Steeper learning curve for developers unfamiliar
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.
milito/query-filter
apiboxsym/user-bundle
apiboxsym/health-check-bundle
jayeshmepani/jpl-moshier-ephemeris-php
elnasnato/laraliveui
labrodev/rest-sdk
sampaui/sampaui
babelqueue/php-sdk
facebook/capi-param-builder-php
babelqueue/symfony
hamzi/corewatch
minionfactory/raw-hydrator
hexters/coinpayment
rjcodes/rjcms
act-training/laravel-permissions-manager
alimarchal/laravel-chart-of-accounts
babenkoivan/elastic-scout-driver
mkwebdesign/filament-watchdog-v5
renatomarinho/laravel-page-speed
zedmagdy/filament-business-hours