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

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 Alignment: The package is a PHPCS (PHP_CodeSniffer) sniff, meaning it integrates seamlessly into existing static analysis pipelines (e.g., CI/CD, pre-commit hooks, or IDE-based linting). This aligns well with Laravel’s reliance on PHP and its ecosystem of tooling (e.g., php-cs-fixer, pest, or custom PHPCS rulesets).
  • Complementary to Laravel’s Patterns:
    • Detects undefined variables (critical for Laravel’s dynamic property access, e.g., $request->input() vs. $request->nonexistent).
    • Flags unused variables (useful for Laravel’s fluent query builder or Eloquent where unused $query or $builder vars may slip through).
    • Catches scope violations (e.g., $this outside classes, relevant for Laravel’s service containers or facades).
  • Performance: The 3.0.x refactor (using phpcsutils) claims 2x speed improvements, mitigating concerns about runtime overhead in large codebases (e.g., Laravel’s monolithic apps or packages).

Integration Feasibility

  • PHPCS Compatibility: Requires PHP_CodeSniffer ≥3.13.5 (Laravel’s default PHPCS version via dealerdirect/phpcodesniffer-composer-installer meets this).
  • Laravel-Specific Hooks:
    • Pre-commit: Integrate via laravel-pint or custom phpcs scripts (e.g., in package.json or composer.json scripts).
    • CI/CD: Add to existing PHPCS jobs (e.g., GitHub Actions, GitLab CI) with minimal config changes.
    • IDE: Supports PHPStorm/VSCode via PHPCS plugins (e.g., PHP_CodeSniffer extension).
  • Dependency Risks:
    • phpcsutils: New dependency in 3.0.x may require composer updates, but it’s a lightweight utility library.
    • PHP 5.4+: Laravel’s minimum PHP version (8.0+) is well above this, so no conflicts.

Technical Risk

  • False Positives/Negatives:
    • Dynamic Properties: Laravel’s #[AllowDynamicProperties] or magic __get() may trigger false "undefined variable" warnings. Mitigation: Use validUndefinedVariableNames or validUndefinedVariableRegexp to whitelist dynamic properties (e.g., $model->dynamic_*).
    • Template Engines: Blade’s @php blocks or global variables (e.g., $_ENV) may need allowUndefinedVariablesInFileScope.
    • Service Container: $app->make() or app()->bind() might confuse static analysis. Mitigation: Exclude vendor files or use ignoreUnusedRegexp for container-related vars.
  • Configuration Complexity:
    • Custom rules (e.g., sitePassByRefFunctions) require XML tweaks. Risk: Overly permissive configs (e.g., allowUnusedVariablesInFileScope) could hide real issues.
  • Breaking Changes:
    • 3.0.x: Backward-compatible per changelog, but phpcsutils dependency may need composer.lock updates.

Key Questions for TPM

  1. Scope of Analysis:
    • Should this run on all PHP files (including Blade, config, or tests) or only app/ and src/?
    • How to handle third-party packages (e.g., Laravel’s core or spatie/laravel-*)? Exclude via PHPCS --exclude or whitelist known vars?
  2. CI/CD Impact:
    • What’s the acceptable failure threshold for new warnings? (e.g., "Fix all undefined vars in PRs" vs. "Warn only on critical paths.")
    • Should this block merges or just log warnings?
  3. Performance:
    • For large repos (e.g., 10K+ files), will PHPCS runtime become a bottleneck? Test with --report=summary first.
  4. Maintenance:
    • Who owns false positive triage? Devs, QA, or a dedicated "code quality" team?
    • How to version-control configs (e.g., phpcs.xml) to avoid drift?

Integration Approach

Stack Fit

  • Laravel Ecosystem:
    • PHPCS Integration: Laravel already uses PHPCS via dealerdirect/phpcodesniffer-composer-installer. This package drops in without disrupting existing tooling.
    • Artisan Commands: Could wrap PHPCS in a custom php artisan phpcs command for consistency.
    • Pint/PHP-CS-Fixer: Runs after PHPCS in typical workflows (fix formatting first, then lint).
  • IDE/Editor:
    • PHPStorm: Native PHPCS support; enable via Settings > PHP > Quality Tools.
    • VSCode: Use the PHP_CodeSniffer extension with phpcs.xml config.
  • Testing:
    • Pest/PHPUnit: Add PHPCS checks to phpunit.xml or pest.php as a pre-test hook.

Migration Path

  1. Phase 1: Pilot (1–2 Sprints)
    • Install in a non-production branch (e.g., feature/phpcs-variable-analysis).
    • Configure minimal rules (e.g., only UndefinedVariable and UnusedVariable).
    • Test on core modules (e.g., app/Http/Controllers) before full rollout.
  2. Phase 2: Gradual Rollout
    • Add to CI/CD (e.g., GitHub Actions) with --report=summary to avoid noise.
    • Use --standard=VariableAnalysis alongside existing standards (e.g., PSR12).
    • Example phpcs.xml snippet:
      <config name="installed_paths" value="./vendor/sirbrillig/phpcs-variable-analysis"/>
      <rule ref="VariableAnalysis">
          <properties>
              <property name="validUndefinedVariableNames" value="request response"/>
              <property name="ignoreUnusedRegexp" value="/^_|^temp/"/>
          </properties>
      </rule>
      
  3. Phase 3: Optimization
    • Tune configs based on false positive data.
    • Exclude known problematic files (e.g., tests/Feature/BladeTest.php) via:
      <file>./tests</file>
      <exclude-pattern>.*/BladeTest\.php</exclude-pattern>
      

Compatibility

  • Laravel-Specific Edge Cases:
    • Dynamic Properties: Use validUndefinedVariableNames to whitelist magic properties (e.g., $model->attributes).
    • Facades: Ignore $this->app->make() vars with ignoreUnusedRegexp=/^app|facade/.
    • Blade Templates: Set allowUndefinedVariablesInFileScope for global vars (e.g., $_ENV, $config).
  • Toolchain Conflicts:
    • PHP-CS-Fixer: Ensure PHPCS runs after fixer to avoid false positives from reformatted code.
    • Psalm/Static Analysis: May overlap with PHPCS; prioritize one tool per concern (e.g., Psalm for types, PHPCS for style).

Sequencing

  1. Pre-requisites:
    • Ensure phpcodesniffer-composer-installer is installed:
      composer require --dev dealerdirect/phpcodesniffer-composer-installer
      
    • Update composer.json to allow plugins:
      "config": {
          "allow-plugins": {
              "dealerdirect/phpcodesniffer-composer-installer": true
          }
      }
      
  2. Installation:
    composer require --dev sirbrillig/phpcs-variable-analysis
    
  3. Configuration:
    • Add to phpcs.xml (see Phase 2 above).
    • Test with:
      vendor/bin/phpcs --standard=VariableAnalysis app/Http/Controllers/
      
  4. CI/CD:
    • Add to .github/workflows/phpcs.yml:
      - name: PHPCS Variable Analysis
        run: vendor/bin/phpcs --standard=VariableAnalysis --report=summary .
      

Operational Impact

Maintenance

  • Configuration Drift:
    • Risk: Team members may override phpcs.xml locally, leading to inconsistent enforcement.
    • Mitigation:
      • Pin configs in .phpcs.dist.xml (committed to repo).
      • Use pre-commit hooks (e.g., husky + simple-phpcs) to enforce standards.
  • Rule Updates:
    • Frequency: New PHPCS/PHP versions may require updates (e.g., 3.0.x’s phpcsutils).
    • Process: Treat as a dependency update (e.g
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.
emuniq/filament-browser-notifications
syriable/filament-translator
hungnm28/livewire-form
wenprise/eloquent
crudly/encrypted
fadion/bouncy
cuci/prototurk-sdk
gos/pubsub-router-bundle
cuci/prototurk-sdk-symfony
clementtalleu/easyadmin-markdown-bundle
codeflextech/permission-manager
karnoweb/livewire-datepicker
sayedenam/sayed-dashboard
milito/query-filter
apiboxsym/user-bundle
apiboxsym/health-check-bundle
jayeshmepani/jpl-moshier-ephemeris-php
elnasnato/laraliveui
labrodev/rest-sdk
sampaui/sampaui