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+.
Installation:
composer require --dev dealerdirect/phpcodesniffer-composer-installer
composer require --dev sirbrillig/phpcs-variable-analysis
Add to your phpcs.xml:
<rule ref="VariableAnalysis"/>
First Use Case: Run PHPCS on a Laravel controller or service:
phpcs app/Http/Controllers/ --standard=VariableAnalysis
Focus on files with undefined variables (e.g., typos) or unused variables (e.g., leftover debug code).
CI/CD Integration:
Add to .github/workflows/phpcs.yml:
- name: Run PHPCS
run: phpcs --standard=VariableAnalysis --extensions=php app/
Fail builds on warnings (adjust severity in phpcs.xml):
<arg name="severity" value="10"/>
Laravel-Specific Customization:
Override defaults in phpcs.xml for Laravel patterns:
<rule ref="VariableAnalysis.CodeAnalysis.VariableAnalysis">
<properties>
<property name="allowUnusedFunctionParameters" value="true"/>
<property name="allowWordPressPassByRefFunctions" value="true"/>
<property name="sitePassByRefFunctions" value="Laravel\Helper\str_replace:1"/>
</properties>
</rule>
Targeted Analysis:
Use --ignore to focus on critical files:
phpcs --standard=VariableAnalysis --ignore="*,tests/*" app/
Pre-Commit Hooks:
Add to .git/hooks/pre-commit:
#!/bin/sh
phpcs --standard=VariableAnalysis --extensions=php --warning-severity=5 "$@"
False Positives in Templates: Disable for Blade templates:
<file>resources/views/*.blade.php</file>
<rule ref="VariableAnalysis.CodeAnalysis.VariableAnalysis">
<properties>
<property name="allowUndefinedVariablesInFileScope" value="true"/>
</properties>
</rule>
Constructor Promotion Confusion:
Ensure sitePassByRefFunctions includes Laravel’s promoted properties:
<property name="sitePassByRefFunctions" value="__construct:1,2,3"/>
Arrow Functions: Nested arrow functions may trigger false negatives. Use:
<property name="allowUnusedForeachVariables" value="false"/>
Global Variables:
Exclude globals like $_ENV or $_SERVER:
<property name="validUndefinedVariableRegexp" value="/^_|^GLOBALS\["/>
phpcs -v --standard=VariableAnalysis app/
phpcs --standard=VariableAnalysis --sniffs=UndefinedVariable app/
Custom Regex:
Ignore magic methods (e.g., __get):
<property name="ignoreUnusedRegexp" value="/^__\w+$|^_"/>
Framework-Specific Rules:
Add Laravel’s app() helper:
<property name="sitePassByRefFunctions" value="app():1"/>
Performance: Cache results in CI:
phpcs --standard=VariableAnalysis --cache-file=.phpcs-cache app/
How can I help you explore Laravel packages today?