• Stars
    star
    135
  • Rank 268,511 (Top 6 %)
  • Language
    PHP
  • License
    Other
  • Created almost 7 years ago
  • Updated 3 months ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Find undefined and unused variables with the PHP Codesniffer static analysis tool.

PHP_CodeSniffer VariableAnalysis

CS and QA Build Status Test Build Status Coverage Status

Plugin for PHP_CodeSniffer static analysis tool that adds analysis of problematic variable use.

  • Warns if variables are used without being defined. (Sniff code: VariableAnalysis.CodeAnalysis.VariableAnalysis.UndefinedVariable)
  • Warns if variables are used inside unset() without being defined. (Sniff code: VariableAnalysis.CodeAnalysis.VariableAnalysis.UndefinedUnsetVariable)
  • Warns if variables are set or declared but never used. (Sniff code: VariableAnalysis.CodeAnalysis.VariableAnalysis.UnusedVariable)
  • Warns if $this, self::$static_member, static::$static_member is used outside class scope. (Sniff codes: VariableAnalysis.CodeAnalysis.VariableAnalysis.SelfOutsideClass or VariableAnalysis.CodeAnalysis.VariableAnalysis.StaticOutsideClass)

Installation

Requirements

VariableAnalysis requires PHP 5.4 or higher and PHP CodeSniffer version 3.5.6 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 config allow-plugins.dealerdirect/phpcodesniffer-composer-installer true
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.

<rule ref="VariableAnalysis"/>

It should just work after that!

Standalone

  1. Install PHP_CodeSniffer (PHPCS) by following its installation instructions (via Composer, Phar file, PEAR, or Git checkout).

    Do ensure that PHP_CodeSniffer's version matches our requirements.

  2. Install VariableAnalysis. Download either the zip or tar.gz file from the VariableAnalysis latest release page. Expand the file and rename the resulting directory to phpcs-variable-analysis. Move the directory to a place where you'd like to keep all your PHPCS standards.

  3. Add the paths of the newly installed standards to the PHP_CodeSniffer installed_paths configuration. The following command should append the new standards to your existing standards (be sure to supply the actual paths to the directories you created above).

     phpcs --config-set installed_paths "$(phpcs --config-show|grep installed_paths|awk '{ print $2 }'),/path/to/phpcs-variable-analysis"
    

    If you do not have any other standards installed, you can do this more easily (again, be sure to supply the actual paths):

     phpcs --config-set installed_paths /path/to/phpcs-variable-analysis
    

Customization

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:

  • allowUnusedFunctionParameters (bool, default false): if set to true, function arguments will never be marked as unused.
  • allowUnusedCaughtExceptions (bool, default true): if set to true, caught Exception variables will never be marked as unused.
  • allowUnusedParametersBeforeUsed (bool, default true): if set to true, unused function arguments will be ignored if they are followed by used function arguments.
  • allowUnusedVariablesBeforeRequire (bool, default false): if set to true, variables defined before a require, require_once, include, or include_once will not be marked as unused. They may be intended for the required file.
  • allowUndefinedVariablesInFileScope (bool, default false): if set to true, undefined variables in the file's top-level scope will never be marked as undefined. This can be useful for template files which use many global variables defined elsewhere.
  • allowUnusedVariablesInFileScope (bool, default false): if set to true, unused variables in the file's top-level scope will never be marked as unused. This can be helpful when defining a lot of global variables to be used elsewhere.
  • validUnusedVariableNames (string, default 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 $junk and $unused, this could be set to 'junk unused'.
  • ignoreUnusedRegexp (string, default 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 $_junk and $_unused, this could be set to '/^_/'.
  • validUndefinedVariableNames (string, default null): a space-separated list of names of placeholder variables that you want to ignore from undefined variable warnings. For example, to ignore the variables $post and $undefined, this could be set to 'post undefined'. This can be used in combination with validUndefinedVariableRegexp.
  • validUndefinedVariableRegexp (string, default null): a PHP regexp string (note that this requires explicit delimiters) for variables that you want to ignore from undefined variable warnings. For example, to ignore the variables $post and $undefined, this could be set to '/^(post|undefined)$/'. This can be used in combination with validUndefinedVariableNames.
  • allowUnusedForeachVariables (bool, default true): if set to true, unused values from the key => value syntax in a foreach loop will never be marked as unused.
  • sitePassByRefFunctions (string, default null): a list of custom functions which pass in variables to be initialized by reference (eg preg_match()) and therefore should not require those variables to be defined ahead of time. The list is space separated and each entry is of the form functionName:1,2. The function name comes first followed by a colon and a comma-separated list of argument numbers (starting from 1) which should be considered variable definitions. The special value ... in the arguments list will cause all arguments after the last number to be considered variable definitions.
  • allowWordPressPassByRefFunctions (bool, default false): if set to true, a list of common WordPress pass-by-reference functions will be added to the list of PHP ones so that passing undefined variables to these functions (to be initialized by reference) will be allowed.

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>

See Also

  • ImportDetection: A set of phpcs sniffs to look for unused or unimported symbols.
  • phpcs-changed: Run phpcs on files, but only report warnings/errors from lines which were changed.

Original

This was forked from the excellent work in https://github.com/illusori/PHP_Codesniffer-VariableAnalysis

Contributing

Please open issues or PRs on this repository.

Any changes should be accompanied by tests and should pass linting and static analysis. Please use phpdoc (rather than actual types) for declaring types since this must run in PHP 5.4.

To run tests, make sure composer is installed, then run:

composer install # you only need to do this once
composer test

To run linting, use:

composer lint

To run static analysis, use:

composer phpstan

More Repositories

1

phpcs-import-detection

A set of phpcs sniffs to look for unused or unimported symbols.
PHP
31
star
2

phpcs-changed

🐘 Run phpcs on files and only report new warnings/errors compared to the previous version.
PHP
31
star
3

gitnews-menubar

Display GitHub notifications in your menu bar
TypeScript
25
star
4

spies

Easier spies, stubs, and mocks for PHP testing
PHP
24
star
5

grepdef

grepdef: search for symbol definitions in various programming languages
Rust
8
star
6

gitnews

A node module to fetch GitHub notifications
JavaScript
6
star
7

vscode-grepdef

This is an extension for vscode that integrates grepdef: search for symbol definitions in various programming languages
JavaScript
5
star
8

humblepress

WordPress tutorial plugin. Creates a simple form that allows writing new posts on a blog with no formatting or metadata. 99% JavaScript.
JavaScript
4
star
9

vim-grepdef

A vim plugin for grepdef: search for symbol definitions in various programming languages
Vim Script
3
star
10

phpcs-no-get-current-user

A phpcs sniff to disallow using get_current_user()
PHP
3
star
11

mixedindentlint

A general-purpose linter for lines that do not match the indentation style of a file
JavaScript
3
star
12

take-the-sky

A game about flying around
JavaScript
3
star
13

copytotheplace

Utility to move files to a configurable and variable place
JavaScript
3
star
14

git-si

Git Svn Interface: a simple git extention to use git locally with a remote svn repo.
Ruby
2
star
15

foolorddotcom

My website.
HTML
2
star
16

voyageur-js-client

An app for calculating driving distances between multiple locations.
JavaScript
2
star
17

two-list

JavaScript
2
star
18

gm18-zero-to-js

Slides for the Zero-to-JS class at the 2018 a8c GM
JavaScript
1
star
19

revealjs-wp

Display a reveal.js slideshow as a WordPress post.
CSS
1
star
20

just-the-snaps

A lightweight snapshot testing library for PHP
PHP
1
star
21

gridmaster2020

JavaScript
1
star
22

lintguard

Run various code linters but only report messages caused by recent changes.
PHP
1
star
23

js-promises-slides

Slides for JS Promises talk
JavaScript
1
star
24

getphpcscoverage

A cli tool which compares a dir with a phpcs config and reports files which are not checked.
JavaScript
1
star
25

mixed-indent-warning-old

[Deprecated] Atom plugin to mark lines that have differing indentation
CoffeeScript
1
star
26

repondez

An RSVP web app.
Ruby
1
star
27

phpcs-wpcom-store-functions

PHP
1
star
28

netgrep

vim plugin for grepping and finding on a remote server using Netrw.
Vim Script
1
star
29

markup-frame

A React component to display raw html markup inside an iframe.
JavaScript
1
star
30

pidify

Ruby gem to background a task (on UNIX) and control it.
Ruby
1
star
31

phabricator-grouping

A Tampermonkey script for collapsing Phabricator notifications to one-per-revision
JavaScript
1
star
32

phb

A stateful Phabricator cli client
TypeScript
1
star
33

tea-information

A WordPress (Gutenberg) block to display information about tea
JavaScript
1
star
34

phabricator-test-reloader

A Tapermonkey script to reload the Phabricator Differential page periodically while tests run
JavaScript
1
star
35

dotfiles

Payton's dotfiles
Vim Script
1
star
36

voyageur-js-server

An API server for the voyageur distance calculation project
JavaScript
1
star
37

gitnews-cli

A simple CLI tool to see your GitHub notifications.
JavaScript
1
star
38

phpunit-just-the-snaps

A lightweight snapshot testing plugin for PHPUnit
PHP
1
star