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 plug gaps in extra-strict setups. Install via Composer, include rules.neon, then enable/disable or tune rules per-project. Targets tricky PHP edge cases like unsafe comparisons, casts, arrays, enums and more.

View on GitHub
Deep Wiki
Context7

Technical Evaluation

Architecture Fit

  • Strictness Alignment: The package aligns well with Laravel’s evolving PHPStan adoption (e.g., Laravel 10+ leverages PHPStan for static analysis). Its super-strict rules complement Laravel’s existing tooling (e.g., Pest, PHPUnit, and native PHPStan) by enforcing type safety, immutability, and exception discipline—critical for large-scale applications.
  • Modularity: Rules are opt-in/opt-out, allowing granular adoption (e.g., enforce readonly properties in PHP 8.2+ while ignoring rules like classSuffixNaming for legacy code).
  • PHP Version Awareness: Rules dynamically adapt to PHP versions (e.g., enforceReadonlyPublicProperty skips PHP 8.0), reducing friction in polyglot environments.

Integration Feasibility

  • Low Friction: Installation via Composer and NEON config mirrors Laravel’s dependency management (e.g., phpstan.neon in phpstan package). No Laravel-specific hooks required.
  • PHPStan Ecosystem Synergy: Rules augment native PHPStan (e.g., enforceNativeReturnTypehint works with Laravel’s return type hints in controllers/services). Compatible with:
    • Laravel’s phpstan-baseline for incremental adoption.
    • Pest/PhpUnit for test-driven enforcement.
  • Configuration Override: Laravel’s environment-based configs (e.g., .env-driven APP_DEBUG) can toggle rules via NEON (e.g., disable forbidCast in local dev).

Technical Risk

Risk Area Mitigation
Rule Overhead Start with a subset of rules (e.g., enforceNativeReturnTypehint, forbidArithmeticOperationOnNonNumber) and measure CI/CD impact before full adoption.
False Positives Leverage PHPStan’s ignoreErrors or rule-specific configs (e.g., allowNumericString: true for forbidArithmeticOperationOnNonNumber).
Backward Compatibility Use excludePaths in NEON to opt-out legacy codebases (e.g., app/OldCode/). Rules like classSuffixNaming can be gradually enforced via superclassToSuffixMapping.
Performance Rules like enforceIteratorToArrayPreserveKeys are lightweight; benchmark in CI to ensure no slowdowns. Cache PHPStan results (--generate-baseline) to offset initial overhead.
Dependency Bloat Package is ~1MB (Composer); negligible compared to Laravel’s core dependencies.

Key Questions for TPM

  1. Adoption Scope:
    • Should rules be mandatory (enforced in CI) or recommended (opt-in via IDE hints)?
    • Example: enforceReadonlyPublicProperty may break legacy code; should it be phased?
  2. Rule Prioritization:
    • Which 3–5 rules offer the highest ROI for Laravel’s codebase? (e.g., forbidCheckedExceptionInCallable for service containers, enforceNativeReturnTypehint for API responses).
  3. CI/CD Integration:
    • Should failures block merges (strict) or warn only (lenient)? Align with Laravel’s existing PHPStan policies.
  4. Customization:
    • Will Laravel need custom rules (e.g., forbidding DB::raw() in queries)? Extend via PHPStan’s extension system.
  5. Documentation:
    • Should the team create Laravel-specific rule guides (e.g., "Why forbidCast matters for Eloquent queries")?

Integration Approach

Stack Fit

  • PHPStan Integration:
    • Native Compatibility: Works with Laravel’s default PHPStan setup (no Laravel-specific plugins needed). Example phpstan.neon:
      includes:
          - vendor/shipmonk/phpstan-rules/rules.neon
      parameters:
          shipmonkRules:
              enforceNativeReturnTypehint: true
              forbidCheckedExceptionInCallable:
                  allowedCheckedExceptionCallables:
                      'Illuminate\Database\Connection::transaction': 0
      
    • Laravel-Specific Tweaks:
      • Disable forbidCast for (array) in Eloquent collections (use blacklist!: ['(array)']).
      • Whitelist Symfony\Component\Console\Command\Command in classSuffixNaming for Artisan commands.
  • Toolchain Synergy:
    • Pest/PhpUnit: Rules like enforceEnumMatch improve test reliability by catching incomplete match statements.
    • Laravel Valet/Sail: Pre-configure PHPStan with rules in docker-compose.yml or Valet templates.
    • IDE Support: Integrate with PHPStorm/VSCode via PHPStan’s inspection plugins for real-time feedback.

Migration Path

  1. Phase 1: Audit & Baseline
    • Run PHPStan with baseline files to capture existing issues:
      vendor/bin/phpstan analyse --generate-baseline app src
      
    • Commit baseline to track progress.
  2. Phase 2: Incremental Enforcement
    • Week 1: Enable low-risk rules (e.g., enforceIteratorToArrayPreserveKeys, forbidArithmeticOperationOnNonNumber).
    • Week 2: Add type-safety rules (e.g., enforceNativeReturnTypehint, allowComparingOnlyComparableTypes).
    • Week 3: Introduce exception discipline (e.g., forbidCheckedExceptionInCallable).
  3. Phase 3: Customization
    • Fine-tune configs (e.g., forbidCast blacklist for Eloquent).
    • Add Laravel-specific stubs (e.g., BackedEnum.php.stub for custom enums).
  4. Phase 4: CI/CD Enforcement
    • Fail builds on rule violations (start with --level 5 in PHPStan).
    • Use GitHub Actions/Laravel Forge to gate merges.

Compatibility

Laravel Component Compatibility Notes
Eloquent Disable (array) casts in forbidCast to avoid breaking Model::toArray().
Service Container forbidCheckedExceptionInCallable may flag closures in bind(); whitelist Illuminate\Container\Container::call().
Artisan Commands Configure classSuffixNaming to enforce Command suffix for \Symfony\Component\Console\Command\Command subclasses.
Blade Templates Rules like enforceNativeReturnTypehint don’t apply; exclude resources/views from analysis.
Legacy Code (PHP < 8.0) Disable PHP-version-specific rules (e.g., enforceReadonlyPublicProperty) via NEON.

Sequencing

  1. Pre-requisites:
    • Upgrade to PHP 8.1+ (required for readonly, enums, and match support).
    • Ensure PHPStan 1.10.34+ (fixes enum analysis issues targeted by enforceEnumMatch).
  2. Order of Rule Activation:
    • Type Safety: enforceNativeReturnTypehintallowComparingOnlyComparableTypes.
    • Immutability: enforceReadonlyPublicProperty (PHP 8.2+).
    • Exceptions: forbidCheckedExceptionInCallableforbidCheckedExceptionInYieldingMethod.
    • Style: classSuffixNaming, enforceClosureParamNativeTypehint.
  3. Post-Integration:
    • Run PHPStan’s analyze with --memory-limit=1G to avoid OOM in large codebases.
    • Use --error-format=github-pr-check for PR-level feedback.

Operational Impact

Maintenance

  • Rule Updates:
    • Monitor ShipMonk’s releases (quarterly updates expected). Test new rules in a staging environment before global adoption.
    • Deprecation Handling: Rules like forbidCast may evolve; use ! in NEON to override defaults (e.g., blacklist!: ['(array)']).
  • Configuration Drift:
    • Store team-specific configs in config/phpstan.php (e.g., custom superclassToSuffixMapping).
    • Use environment variables to toggle rules (e.g., PHPSTAN_RULES_STRICT=1 in CI).
  • **Dependency Management
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.
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
renatovdemoura/blade-elements-ui
devgeek/beacon-admin
benjamin-rqt/data-watcher-bundle
atriumphp/atrium
sandermuller/package-boost-laravel
sandermuller/boost-skills
redaxo/core