Plugin for PHP_CodeSniffer static analysis tool that adds analysis of problematic variable use.
- Performs static analysis of variable use.
- Warns on use of undefined variables.
- Warns if variables are set or declared but never used within that scope.
- Warns if variables are redeclared within same scope.
- Warns if $this, self::$static_member, static::$static_member is used outside class scope.
VariableAnalysis requires PHP 5.4 or higher and PHP CodeSniffer version 3.0.2 or higher.
With PHPCS Composer Installer
This is the easiest method.
First, install phpcodesniffer-composer-installer for your project if you have not already. This will also install PHPCS.
composer require --dev dealerdirect/phpcodesniffer-composer-installer
Then install these standards.
composer require --dev sirbrillig/phpcs-variable-analysis
You can then include the sniffs by adding a line like the following to your phpcs.xml file.
It should just work after that!
Install PHP_CodeSniffer by following its installation instructions (via Composer, Phar file, PEAR, or Git checkout).
Do ensure that PHP_CodeSniffer's version matches our requirements
Clone the repository:
git clone -b master https://github.com/sirbrillig/VariableAnalysis.git VariableAnalysis
Add its path to the PHP_CodeSniffer configuration:
phpcs --config-set installed_paths /path/to/VariableAnalysis
If you already have installed paths, use a comma to separate them.
There's a variety of options to customize the behaviour of VariableAnalysis, take a look at the included ruleset.xml.example for commented examples of a configuration.
The available options are as follows:
false): if set to true, function arguments will never be marked as unused.
false): if set to true, caught Exception variables will never be marked as unused.
null): a space-separated list of names of placeholder variables that you want to ignore from unused variable warnings. For example, to ignore the variables
$unused, this could be set to
null): a PHP regexp string (note that this requires explicit delimiters) for variables that you want to ignore from unused variable warnings. For example, to ignore the variables
$_unused, this could be set to
To set these these options, you must use XML in your ruleset. For details, see the phpcs customizable sniff properties page. Here is an example that ignores all variables that start with an underscore:
<rule ref="VariableAnalysis.CodeAnalysis.VariableAnalysis"> <properties> <property name="ignoreUnusedRegexp" value="/^_/"/> </properties> </rule>
- ImportDetection: A set of phpcs sniffs to look for unused or unimported symbols.
This was forked from the excellent work in https://github.com/illusori/PHP_Codesniffer-VariableAnalysis
Please open issues or PRs on this repository.
To run tests, make sure composer is installed, then run:
composer install # you only need to do this once composer test