Byte Ebi's Logo

Byte Ebi 🍀

A Bit everyday A Byte every week

Using PHP CodeSniffer to Check Coding Style

Checking and correcting coding style using phpcs and phpcbf

Ray

Checking code conformity with standards using phpcs (PHP Code Sniffer)
Automatically correcting non-conforming code using phpcbf (PHP Code Beautifier and Fixer)

PHP CodeSniffer

PHP_CodeSniffer is a tool used to check if code conforms to standards.
It consists of two PHP scripts: phpcs and phpcbf.

  • phpcs: Checks PHP, JavaScript, and CSS files for compliance with specified coding styles.
  • phpcbf: Automatically corrects code that does not conform to standards.

Installation and Usage

Instructions on setting up the configuration file phpcs.xml for checks were previously covered in the blog post Using GrumPHP as a Gatekeeper for Code Quality , so we won’t repeat them here.

Local Installation

Installation command:

composer global require 'squizlabs/php_codesniffer=*'

For users of oh-my-zsh, additional manual configuration is required:

vim ~/.zshrc

Add:

export PATH=$HOME/bin:/usr/local/bin:/Users/[your-user-name]/.composer/vendor/bin:$PATH

Reload the configuration and check the installed version:

source ~/.zshrc

which phpcs

phpcs --version

Changing Prompt Message Color Settings

phpcs --config-set colors 1

Executing Custom Coding Style Checks

If you have a custom coding style, you need to specify the phpcs.xml configuration file to execute the checks:

phpcs --standard={/path/to/custom_phpcs.xml} {/path/to/project/or/file}

Changing Default Coding Style

phpcs --config-set default_standard ../../phpcs.xml

You can also switch to other PSR standards:

phpcs --config-set default_standard PSR2

Setting Default Coding Style

The original default is PSR-2, which can be changed to your own version:

phpcs --config-set default_standard ../../phpcs.xml

Checking and Automatically Correcting Formatting Using Defaults

phpcs {/path/to/project/or/file}

phpcbf {/path/to/project/or/file}

Usage in a Project

If you want to configure it in a project and include it in the Continuous Integration (CI) process for automatic execution, you can add it directly to the project for easy, unified configuration:

composer require --dev squizlabs/php_codesniffer

./vendor/bin/phpcs -h
./vendor/bin/phpcbf -h

Recent Posts

Categories

Tags