PHP Sniffer
Uses PHP_CodeSniffer to format and lint PHP code.
Features
- Runs
phpcs
to lint PHP code. - Runs
phpcbf
to format fixable PHP code validation errors, using the built-in commands "Format Document" or "Format Selection".- One may need to set this extension as the default PHP language formatter if
you have more than one PHP language extension enabled. Use the following
snippet in a
settings.json
:{ "[php]": { "editor.defaultFormatter": "wongjn.php-sniffer" } }
- One may need to set this extension as the default PHP language formatter if
you have more than one PHP language extension enabled. Use the following
snippet in a
Requirements
Extension Settings
Quick Setup
settings.json
:
{
"phpSniffer.autoDetect": true
}
And if your projects look like this:
workspace-folder/
vendor/
bin/
phpcs
phpcbf
.phpcs.xml
Validation and formatting will work (see below for alternative filenames for
.phpcs.xml
).
In Depth
This extension contributes the following settings:
phpSniffer.run
: When to runphpcs
(the linter). Can beonSave
oronType
.phpSniffer.onTypeDelay
: WhenphpSniffer.run
isonType
, this sets the amount of milliseconds the validator will wait after typing has stopped before it will run. The validator will also cancel an older run if the run is on the same file.phpSniffer.executablesFolder
: The folder where bothphpcs
andphpcbf
executables are. Use this to specify a different executable if it is not in your globalPATH
, such as when usingPHP_Codesniffer
as a project-scoped dependency. Can be absolute, or relative to the workspace folder.phpSniffer.autoDetect
: Set totrue
for the extension to auto-detectphpSniffer.executablesFolder
as./vendor/bin/
per workspace folder (applies only ifphpSniffer.executablesFolder
is empty).phpSniffer.standard
: The standards to check against. This is passed to thephpcbf
andphpcs
executables as the value for--standard
. Can be absolute, or relative to the workspace folder. If not set, PHP_CodeSniffer will attempt to find a file to use, at the root of the currently open file's workspace folder in the following order:.phpcs.xml
phpcs.xml
.phpcs.xml.dist
phpcs.xml.dist
phpSniffer.snippetExcludeSniffs
: Sniffs to exclude when formatting a code snippet (such as when formatting on paste or on the commandformat on selection
). This is passed to thephpcbf
command as the value for--exclude
when not formatting a whole file.
Known Issues
Windows Hanging PHP Process
When phpcs
encounters a malformed array declaration, it can sometimes hang from an error.
This is exacerbated by the fact that we do not have access to the spawned php
process in the extension code and cannot kill php.exe
directly. This causes
many non-exiting PHP processes on Windows machines which can really slow down
the machine.
The fix for this is to update squizlabs/PHP_Codesniffer
in use to >=3.4.2
.