PHP CodeSniffer (PHPcs)

From HaFrWiki
Jump to: navigation, search

PHP CodeSniffer (PHPcs) is a useful tool for PHP developers [1].

Introduction

PHPcs is a PHP5 script that tokenises and "sniffs" PHP, JavaScript and CSS files to detect violations of a defined coding standard. It is an essential development tool that ensures your code remains clean and consistent. It can also help prevent some common semantic errors made by developers.

Installation

The preferred way to install PHPcs is PHP Composer.

$ composer global require "squizlabs/php_codesniffer=*"

Optional on Unix/Mac Operating Systems create a shortcut (Symbolic Link) to the installed version, which is located in the subdirection of the location of the used composer.json.
Most users will create a directory .composer under the used user ~.
Example ~/.composer directory:

-d- cache
-d- vendor
    -d- bin 
        -s- pdepend
        -s- php-cs-fixer
        -s- phpcs
        -s- phpmd
        -s- phpstan
        -s- phpstan.phar
-f- composer.lock
-f- composer.json
-?- ...
  • -d- : directory.
  • -f- : file.
  • -s- : symbolic link or alias.
  • -?- : other files.

Example composer.json after installation.

 1 {
 2   "require": {
 3      "squizlabs/php_codesniffer": "3.*",
 4      "friendsofphp/php-cs-fixer": "^3.0"
 5   },
 6
 7   "require-dev": {
 8      "phpmd/phpmd"  : "@stable",
 9      "phpstan/phpstan": "^0.12.87"
10   }
11 }

Please note: The line 3 shows the added phcs-entry.

Bug Workarounds

If you install using the composer method the following is DEPRECATED. So this only applies to the pear installation before 2019.
Some users experience warning about not finding the CLI.php file after installing and trying the tools.

  • Search for the location of the phpcs file.
  • open the file with a normal developer text editor.
  • Adjust
if (is_file(dirname(__FILE__).'/../CodeSniffer/CLI.php') === true) {
   include_once dirname(__FILE__).'/../CodeSniffer/CLI.php';
else {
   include_once 'PHP/CodeSniffer/CLI.php';
}

Into something like:

if (is_file(dirname(__FILE__).'/../CodeSniffer/CLI.php') === true) {
   include_once dirname(__FILE__).'/../CodeSniffer/CLI.php';
} else if (is_file('/usr/local/pear/share/pear/PHP/CodeSniffer/CLI.php')) {
   include_once '/usr/local/pear/share/pear/PHP/CodeSniffer/CLI.php';
} else {
   include_once 'PHP/CodeSniffer/CLI.php';
}

See also

top

Reference

top

  1. 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.