How to set up PHPCS?

PHPCS stands for PHP_CodeSniffer. It is used to check and detect PHP coding standards. Let’s discuss how to set up PHPCS.

It included two main scripts phpcs and phpcbf. Among them phpcs checks standards of PHP, CSS and JavaScript files and will show the appropriate errors with some helpful context. And phpcbf automatically corrects the coding standards in files.

We must use PHP_CodeSniffer to ensure our code remains consistent and clean. We need PHP version 5.4.0 or greater to run PHP_CodeSniffer.

There are multiple methods to set up PHPCS. But let’s go with the Composer & Phive method.

Setup with Composer

Run the following command system-wide.

composer global require "squizlabs/php_codesniffer=*"

Or alternatively, include a dependency for squizlabs/php_codesniffer in your composer.json file. For example:

{
    "require-dev": {
        "squizlabs/php_codesniffer": "3.*"
    }
}

Setup with Phive

Run the following command.

phive install phpcs
phive install phpcbf

You will then be able to run PHP_CodeSniffer from the tools directory:

./tools/phpcs -h
./tools/phpcbf -h

Check if PHPCS is installed properly

If you’ve got the successfully installed message of PHPCS in your terminal. Then you can check with the following command.

phpcs -i

You will see the below options with all supported standards. It is showing many more because I’ve already added some other standards related to WordPress.

All coding standards with PHPCS

How to check our code with PHPCS

To validate your code you need to run the following phpcs command.

phpcs --standard=PSR12 FILE_PATH

Update PSR12 with your needed full standards like PSR2, WordPress, etc. and FILE_PATH with your actual file path. See the below image for a clear understanding.

PHPCS test.

Check PHPCS Config

phpcs --config-show
Share this:

Related Post

Find Out How to Leverage Powerful New Features in PHP 8 vs PHP 7

Find Out How to Leverage Powerful New Features in PHP 8 vs PHP 7

PHP match Expression

PHP match Expression

What is new in PHP 8

What is new in PHP 8