Weave 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

Phpcs Variable Analysis Laravel Package

sirbrillig/phpcs-variable-analysis

PHPCS plugin that analyzes variable usage: warns on undefined variables (including in unset), unused variables, and use of $this/self/static outside class scope. Works with PHPCS 3.13.5+ and PHP 5.4+.

View on GitHub
Deep Wiki
Context7

Technical Evaluation

Architecture Fit

  • Static Analysis Tooling: The package integrates seamlessly into PHP_CodeSniffer (PHPCS), a widely adopted static analysis tool for PHP. This aligns well with Laravel’s existing PHPStan, Psalm, and PHPUnit ecosystem, enabling complementary rather than disruptive adoption.
  • Laravel-Specific Use Cases:
    • Detects undefined variables (common in dynamic template files, e.g., Blade templates with global variables).
    • Identifies unused variables (critical for refactoring legacy Laravel apps with verbose variable declarations).
    • Catches misused $this/static (relevant in Laravel’s service container and facades).
  • Non-Invasive: Operates at the codebase level (no runtime overhead) and integrates via PHPCS rulesets, avoiding modifications to Laravel’s core or business logic.

Integration Feasibility

  • PHPCS Compatibility: Requires PHPCS ≥3.13.5 (Laravel’s default PHPCS version via dealerdirect/phpcodesniffer-composer-installer meets this).
  • Laravel CI/CD Fit:
    • Can be gated in PRs (e.g., GitHub Actions) alongside existing static analysis tools.
    • Works with Laravel Forge/Envoyer for deployment-time validation.
  • Toolchain Synergy:
    • Pairs with phpcs-changed (from the same author) to skip unchanged files, reducing CI noise.
    • Complements PHPStan/Psalm by catching dynamic analysis blind spots (e.g., variables defined via eval or dynamic includes).

Technical Risk

Risk Area Mitigation Strategy
False Positives Customize via ruleset.xml (e.g., whitelist globals like $_ENV, config()).
Performance PHPCS runs incrementally; cache results with phpcs --cache.
PHPCS Version Drift Pin PHPCS version in composer.json to avoid breaking changes.
Template Files Configure allowUndefinedVariablesInFileScope for Blade templates.
Legacy Code Start with --report=summary to avoid overwhelming teams with warnings.

Key Questions for TPM

  1. Adoption Scope:
    • Should this run only in CI (strict) or locally (developer-friendly)?
    • Will it replace or augment existing tools (e.g., PHPStan’s noUnusedVars)?
  2. Customization Needs:
    • Are there framework-specific globals (e.g., $request, app()) to whitelist?
    • Should WordPress pass-by-ref functions (if used) be enabled via allowWordPressPassByRefFunctions?
  3. CI Integration:
    • Should failures block merges or be warn-only initially?
    • How to handle large codebases (e.g., parallelize PHPCS runs)?
  4. Maintenance:
    • Who owns ruleset.xml updates (e.g., adding new exceptions)?
    • Should this be vendor-locked or project-wide?

Integration Approach

Stack Fit

  • PHPCS Ecosystem: Leverages Laravel’s existing dealerdirect/phpcodesniffer-composer-installer for zero-config installation.
  • Toolchain Placement:
    • Pre-Commit Hook: Use phpcs-changed to analyze only modified files (via roave/security-advisories or custom script).
    • CI Pipeline: Run in parallel with PHPStan/Psalm (e.g., GitHub Actions matrix).
  • Laravel-Specific Optimizations:
    • Blade Templates: Exclude or configure allowUndefinedVariablesInFileScope for dynamic globals.
    • Service Container: Ignore $this misuse in facades via validUndefinedVariableNames.

Migration Path

  1. Phase 1: Pilot
    • Install in a non-critical branch:
      composer require --dev sirbrillig/phpcs-variable-analysis
      
    • Add to phpcs.xml:
      <rule ref="VariableAnalysis" />
      
    • Test with --report=summary to assess noise.
  2. Phase 2: Customization
    • Create a project-specific ruleset.xml (e.g., phpcs-ruleset.xml) to:
      • Whitelist Laravel globals (e.g., $request, config()).
      • Adjust allowUnusedFunctionParameters for legacy APIs.
    • Example:
      <rule ref="VariableAnalysis.CodeAnalysis.VariableAnalysis">
          <properties>
              <property name="validUndefinedVariableNames" value="request config app" />
              <property name="allowUnusedFunctionParameters" value="true" />
          </properties>
      </rule>
      
  3. Phase 3: CI Integration
    • Add to .github/workflows/phpcs.yml:
      - name: PHP_CodeSniffer
        run: phpcs --standard=phpcs-ruleset.xml --report=full src/
      
    • Configure failure thresholds (e.g., block on critical errors only).

Compatibility

Component Compatibility Notes
PHP 8.x Fully supported (package requires PHP ≥5.4).
Laravel 9/10 No conflicts; PHPCS operates on abstract syntax.
Blade Templates Requires allowUndefinedVariablesInFileScope for dynamic globals.
Composer Uses phpcodesniffer-composer-installer (no manual PHPCS installation needed).
Windows/Linux Cross-platform (PHPCS is agnostic).

Sequencing

  1. Prerequisite: Ensure PHPCS ≥3.13.5 is installed (handled by phpcodesniffer-composer-installer).
  2. Installation: Add to composer.json (dev dependency).
  3. Configuration: Create phpcs-ruleset.xml before enabling in CI.
  4. Validation: Run locally first to catch misconfigurations.
  5. CI Rollout: Start with warn-only, then enforce based on feedback.

Operational Impact

Maintenance

  • Ruleset Updates:
    • Low Effort: Custom rules (e.g., whitelists) can be version-controlled in phpcs-ruleset.xml.
    • Automation: Use phpcs --generate=ruleset to scaffold updates.
  • Dependency Management:
    • Pin sirbrillig/phpcs-variable-analysis and phpcsutils in composer.json to avoid surprises.
    • Monitor for PHPCS major versions (e.g., 4.0+) that may require reconfiguration.
  • Tooling Drift:
    • False Positives: Address via validUndefinedVariableNames or ignoreUnusedRegexp.
    • Performance: Cache PHPCS results with --cache in CI.

Support

  • Onboarding:
    • Documentation: Add a CONTRIBUTING.md section on PHPCS ruleset customization.
    • Examples: Provide a template phpcs-ruleset.xml for Laravel projects.
  • Troubleshooting:
    • Common Issues:
      • "Too many warnings": Start with --ignore=* and gradually enable rules.
      • Blade template false positives: Use allowUndefinedVariablesInFileScope.
    • Debugging: Use phpcs --verbose and --report=emacs for detailed output.
  • Escalation Path:
    • For edge cases (e.g., dynamic eval), open issues in the repo.

Scaling

  • Large Codebases:
    • Parallelization: Split PHPCS runs by directory (e.g., phpcs src/ app/ tests/ in parallel).
    • Incremental Analysis: Use phpcs-changed to analyze only modified files.
  • Performance:
    • Baseline: PHPCS adds ~5–10s to CI for 10K LOC (varies by complexity).
    • Optimizations:
      • Cache results with --cache.
      • Exclude vendor/ and node_modules/ from analysis.
  • Distributed Teams:
    • Local vs. CI: Allow local runs with --ignore=* but enforce in CI.
    • Custom Rules: Share phpcs-ruleset.xml via team templates.

Failure Modes

Failure Mode Impact Mitigation
False Positives Developer frustration Customize ruleset; start with --ignore=*
PHPCS Version Conflict Build failures Pin PHPCS version in `composer.json
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.
andydefer/laravel-notification
adachsoft/cli-process-tester
jhaskell13/laraflow
sebastienheyd/boilerplate-media-manager
ccast/tagixo-primix
pretendtrue/laravel-builder
sawmainek/laravel-scout-tntsearch-driver
tomshaw/laravel-calendar-table
dibakar/laravel-ownership
steadrun/laravel-monitor
labyrinthe/connect-laravel
elmogy/layan
drewdan/sentinel-client
dskripchenko/laravel-llm
fatryst/nuonuo
stevenay/myanfont
gmostafa/php-graphql-client
xeviant/paystack
snowsoft/faker
meditationsteps/blogetc