How to use PHP CodeSniffer with VSCode

CodeSniffer

When using VSCode to write code it would be great if you could have CodeSniffer to automatically run coding standard checks while you code. You can do this through the use of a plugin that can be added with VSCode.

You will require CodeSniffer to be setup on your PC, open the terminal and try using the CodeSniffer command to make sure it is working.

phpcs --version

Setup CodeSniffer in VSCode

Open up the VSCode application and go to the Extensions section in the left hand menu.

In the search type in “codesniffer” and look for the plugin named PHP Sniffer & Beautifier by Samuel Hilson.

plugin2.png

On the plugin page click the gear icon, in the dropdown menu click the Extension Settings option to open up the settings page.

plugin-settings.png

In the new tab that appears scroll down and find the Sniffer Mode section, change the option from onSave to onType to run CodeSniffer on key presses instead of when the file is saved.

plugin-sniffer-mode.png

Find the Standard section and click the Edit in settings.json link.

plugin-sniffer-standard.png

In the new tab which shows the contents of the settings.json file, set the coding standard you want to use like PSR-12 for example.

plugin-settings-json.png

So whenever you type in code and the code doesn’t comply with the selected coding standard then you will see error highlights which show the errors when you hover over them.

plugin-sniffer-error.png

If the errors don’t show when they are supposed to try restarting VSCode as the PHP Sniffer & Beautifier extension may need to be reloaded.