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

Getting Started

Minimal Setup

  1. Installation:

    composer require --dev sirbrillig/phpcs-variable-analysis
    

    Add to your phpcs.xml:

    <rule ref="VariableAnalysis"/>
    
  2. First Use Case: Run PHPCS on a file to detect undefined/unused variables:

    phpcs app/YourController.php
    

    Example output:

    FILE: app/YourController.php
    ----------------------------------------------------------------------
    FOUND 2 ERROR(S) AND 1 WARNING(S) AFFECTING 2 LINE(S)
    ----------------------------------------------------------------------
      10 | ERROR   | Undefined variable: $undefinedVar
      20 | WARNING | Unused variable: $unusedVar
    
  3. Key Files:

    • ruleset.xml.example (for customization)
    • src/VariableAnalysis/CodeAnalysis/VariableAnalysis.php (core logic)

Implementation Patterns

Daily Workflow

  1. Integrate into CI/CD: Add PHPCS to your pipeline (e.g., GitHub Actions):

    - name: Run PHPCS
      run: phpcs --standard=VariableAnalysis --extensions=php .
    
  2. Targeted Scans: Focus on critical files:

    phpcs app/ --standard=VariableAnalysis --report=full
    
  3. Custom Rulesets: Create a project-specific phpcs.xml:

    <ruleset>
        <rule ref="VariableAnalysis">
            <properties>
                <property name="allowUnusedFunctionParameters" value="true"/>
                <property name="validUnusedVariableNames" value="tmp debug"/>
            </properties>
        </rule>
    </ruleset>
    

Common Use Cases

  • Debugging: Detect typos in variable names (e.g., $user vs $users).
  • Refactoring: Identify dead code via unused variables.
  • Onboarding: Enforce consistent variable usage across teams.

Integration Tips

  • Combine with Other Sniffs: Use alongside SquizLabs_PHP_CodeSniffer or PSR12 for broader coverage.
  • Custom Exceptions: Extend VariableAnalysis by subclassing VariableAnalysis and overriding methods like process().
  • Performance: Cache results for large codebases using PHPCS’s --cache flag.

Gotchas and Tips

Pitfalls

  1. False Positives:

    • Global Variables: Set allowUndefinedVariablesInFileScope="true" for template files.
    • Dynamic Includes: Use allowUnusedVariablesBeforeRequire="true" for files with require_once.
    • Pass-by-Reference: Configure sitePassByRefFunctions for custom functions like:
      <property name="sitePassByRefFunctions" value="my_func:1,2"/>
      
  2. Scope Issues:

    • Arrow Functions: Ensure nested arrow functions are detected by updating PHPCS to ≥3.13.5.
    • Anonymous Classes: Use simplify detecting class properties (v2.11.20+) for accurate property analysis.
  3. Configuration Conflicts:

    • Override defaults in phpcs.xml after the base rule:
      <rule ref="VariableAnalysis.CodeAnalysis.VariableAnalysis">
          <properties>
              <property name="ignoreUnusedRegexp" value="/^_/"/>
          </properties>
      </rule>
      

Debugging Tips

  • Verbose Output: Run with --verbose to see sniff execution details:
    phpcs --standard=VariableAnalysis --verbose app/Controller.php
    
  • Test Sniffs Isolated: Use PHPCS’s --sniffs flag to test individual sniffs:
    phpcs --sniffs=VariableAnalysis app/ --report=json
    
  • Regex Debugging: Validate ignoreUnusedRegexp patterns with PHP’s preg_match() before applying.

Extension Points

  1. Custom Sniffs: Extend the base sniff by copying VariableAnalysis.php and modifying:

    • init(): Add new properties.
    • process(): Inject custom logic (e.g., ignore variables in specific namespaces).
  2. PHPCSUtils Integration: Leverage phpcsutils (dependency since v3.0.0-beta.9) for advanced AST traversal:

    use PHPCSUtils\Token\TokenUtils;
    // Example: Check for variable usage in a specific context.
    
  3. Performance Tuning:

    • Disable sniffs for large files:
      <exclude-pattern>*/tests/*</exclude-pattern>
      
    • Use --parallel for multi-core processing (PHPCS ≥3.6.0).

Pro Tips

  • Template Files: For Blade/Laravel templates, combine with phpcs-changed to avoid false positives in dynamic files.
  • Legacy Code: Gradually enable sniffs using --ignore:
    phpcs --ignore=UndefinedVariable app/legacy/
    
  • WordPress: Enable pass-by-reference functions:
    <property name="allowWordPressPassByRefFunctions" value="true"/>
    

```markdown
### Laravel-Specific Notes
1. **Service Container**:
   Ignore container-bound variables (e.g., `$app`) by adding to `validUndefinedVariableNames`:
   ```xml
   <property name="validUndefinedVariableNames" value="app container"/>
  1. Eloquent Models: Exclude model properties from unused checks if dynamically populated:

    <property name="ignoreUnusedRegexp" value="/^_|^relation_|^attribute_"/>
    
  2. Facades: Mark facade variables (e.g., $cache) as valid to avoid conflicts with global helpers:

    <property name="validUndefinedVariableNames" value="cache auth request"/>
    
  3. Artisan Commands: Use allowUnusedParametersBeforeUsed="true" for CLI arguments:

    <rule ref="VariableAnalysis.CodeAnalysis.VariableAnalysis">
        <properties>
            <property name="allowUnusedParametersBeforeUsed" value="true"/>
        </properties>
    </rule>
    
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.
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
renatovdemoura/blade-elements-ui
devgeek/beacon-admin
benjamin-rqt/data-watcher-bundle