Skip to content

PHP Linting Guide

Rehan Nagoor Mohideen edited this page May 18, 2024 · 1 revision

PHP_CodeSniffer for PHP Linting (CI/CD)

Research for CodeSniffer by Ivan Odiel Magtangob

Resources:

  1. https://github.com/squizlabs/PHP_CodeSniffer
  2. https://github.com/squizlabs/PHP_CodeSniffer/wiki/Configuration-Options

1. What is PHP_CodeSniffer?

PHP_CodeSniffer is a set of two PHP scripts; the main phpcs script that tokenizes PHP, JavaScript and CSS files to detect violations of a defined coding standard, and a second phpcbf script to automatically correct coding standard violations. PHP_CodeSniffer is an essential development tool that ensures your code remains clean and consistent.

2. Installation

To avoid modifying the VM, the two PHP_CodeSniffer scripts were installed into the repository using curl:

curl -OL https://squizlabs.github.io/PHP_CodeSniffer/phpcs.phar
curl -OL https://squizlabs.github.io/PHP_CodeSniffer/phpcbf.phar

3. Usage

To use either script:

phpcs /path/to/code/myfile.php
phpcbf /path/to/code/myfile.php

4. Configuration

PHP_CodeSniffer can be further configured to ignore certain warnings, enable coloured output messages, etc.. Settings such as these can be implemented in a CodeSniffer.conf file:

<?php
 $phpCodeSnifferConfig = array (
  'colors' => '1',
  'ignore_warnings_on_exit' => '1',
);
?>

Some other configuration options can also be added within the PHP files to be linted, or specified in the command when executing the script. For example, to ignore all of a certain error:

phpcs --exclude=Generic.Files.LineEndings /path/to/code/myfile.php
Clone this wiki locally