Do You PHP はてブロ

Do You PHPはてなからはてブロに移動しました

PHP_CodeSniffer


PHP_CodeSniffer is a PHP5 script that tokenises and "sniffs" PHP code to detect violations of a defined set of coding standards. It is an essential development tool that ensures that your code remains clean and consistent. It can even help prevent some common semantic errors made by developers.

PHPスクリプトのコーディングルールチェックツールで、JavaでいうCheckstyleに相当するようなツールです。
このパッケージにはphpcsコマンドが含まれていて、CLIの場合これを使用するようです。

$ phpcs
ERROR: You must supply at least one file or directory to process.

Usage: phpcs [-nvi] [--report=<report>] [--standard=<standard>] <file> ...
 <file>     : one or more files and/or directories to check
 <standard> : the name of the coding standard to use
 <report>   : print either the "full" or "summary" report
 -n         : do not print warnings
 -v         : print verbose output
 -i         : show a list of installed coding standards
 -h --help  : print this help message
 --version  : print version information
$ 

現在は、PEARのルールのみ対応しているようですが、--standardオプションを使って後々色々なコーディングルールに対応できるようです。
ちなみに実行結果はこんな感じです。

$ phpcs /path/to/sample.php

FILE: /path/to/sample.php
--------------------------------------------------------------------------------
FOUND 15 ERROR(S) AND 3 WARNING(S) AFFECTING 15 LINE(S)
--------------------------------------------------------------------------------
[LINE 3] ERROR: Line indented incorrectly. Expected 0 spaces but found 1.
[LINE 4] ERROR: Line indented incorrectly. Expected at least 4 spaces, but found 2.
[LINE 7] ERROR: Line indented incorrectly. Expected 0 spaces but found 1.
[LINE 8] ERROR: Line indented incorrectly. Expected at least 4 spaces, but found 2.
[LINE 15] ERROR: Space after opening parenthesis of function call prohibited
[LINE 17] WARNING: Equals sign not aligned with surrounding assignments. Expected 3 spaces, but found 2 spaces.
[LINE 22] ERROR: Space before closing parenthesis of function call prohibited
[LINE 25] ERROR: Line indented incorrectly. Expected 0 spaces but found 4.
[LINE 28] ERROR: Line indented incorrectly. Expected 0 spaces but found 4.
[LINE 37] ERROR: No space found after comma.
[LINE 43] ERROR: Line indented incorrectly. Expected 0 spaces but found 4.
[LINE 44] WARNING: Equals sign not aligned correctly. Expected 1 space, but found 2 spaces.
[LINE 44] ERROR: No space found after comma.
[LINE 49] ERROR: Expected "while (...) {\n" found "while(...)\n    {\n".
[LINE 49] ERROR: Line indented incorrectly. Expected 0 spaces but found 4.
[LINE 52] ERROR: Line indented incorrectly. Expected 4 spaces but found 8.
[LINE 53] WARNING: Equals sign not aligned correctly. Expected 1 space, but found 2 spaces.
[LINE 53] ERROR: No space found after comma.
--------------------------------------------------------------------------------
$