PHP_CodeSniffer in VSCode Using the phpcs Extension

In our previous article, we discussed how to use the PHP_CodeSniffer scripts from the command line to verify our code matches the standards we’ve created. The huge downside to that process is that we’re constantly having to switch between our editor and our terminal to check our code. It’s enough to make us want to pull out our hair.

In this article, we’ll discuss how to use the phpcs extension for Visual Studio Code to check our code as we write it.

Which Extension?

One of the downsides to using the extension Marketplace for VS Code is that it can be a real pain trying to find which extension to use.

For example, if we search for “phpcs” we get 15 results the first two results are the phpcs extension with the same icon but different developers. For this article, we’re going to use the extension developed by Ioannis Kappas (https://marketplace.visualstudio.com/items?itemName=ikappas.phpcs) because it’s been around longer and has the most downloads.

Installation

Installation is as easy as clicking the “Install” button but we do need to configure it. The phpcs script doesn’t come with the extension so we’ll need to install that first. After that’s done we need to open our VS Code settings (command + ,) and then search for phpcs. The first thing we need to enter is the “Phpcs: Executable Path” setting which will list where the phpcs script can be found. In this example, we installed it globally (even though we said to install it per project earlier).

Next, we need to configure the standard we’re going to check our code against. We have a couple, of options for how we can configure this.

The first is to set the default standard in the phpcs script’s settings

phpcs --config-set default_standard <value>
./vendor/bin/phpcs --config-set default_standard <value>

The other is that we can specify the standard inside our “settings.json” file.

{
    "phpcs.standard": "PSR12"
}

Mostly this is a personal preference. We like putting it in the “settings.json” file because we can easily move it to another computer but setting the standard in the command line sets it for PHP Code Beautifier and Fixer too.

Usage

Using this extension is super easy we just write our code as we normally would. Then if we deviate from the standard we’ll get a red wavy line at the point of the error and we can hover over it to see what we need to fix.

Unfortunately, this extension doesn’t automatically reformat our code to fix the errors. We still have to run PHP Code Beautifier and Fixer manually to get it to fix our errors or find another extension that will do that for us.

We’re a big fan of not installing an extension to do this because by just showing us the errors and manually fixing them we’ll train ourselves to use the correct syntax and have less of a need for the PHP Code Beautifier and Fixer script. It’s not zero but it’s not all the time either.