【PHP】PHP_CodeSnifferを使う(コーディングルールのカスタマイズ)

phpcsを社内独自のコーディン規約などにあわせてカスタマイズする方法をまとめます。

インストールディレクトリ

以下のディレクトリにインストールされてます。

~/.composer/vendor/squizlabs/php_codesniffer/

-rw-r--r--   1   638 10 28 13:36 CONTRIBUTING.md
-rw-r--r--   1   187 11 26 12:08 CodeSniffer.conf.dist
-rw-r--r--   1  6399 10 28 13:36 README.md
-rw-r--r--   1 10085 10 28 13:36 autoload.php
drwxr-xr-x   6   192 10 28 13:36 bin
-rw-r--r--   1  1083 10 28 13:36 composer.json
-rw-r--r--   1  1533 10 28 13:36 licence.txt
-rw-r--r--   1  6280 10 28 13:36 phpcs.xml.dist
-rw-r--r--   1  7054 10 28 13:36 phpcs.xsd
-rw-r--r--   1   340 10 28 13:36 phpstan.neon
drwxr-xr-x   5   160 10 28 13:36 scripts
drwxr-xr-x  16   512 10 28 13:36 src
drwxr-xr-x   9   288 10 28 13:36 tests

設定ファイルを用意する

CodeSniffer.conf.dist が雛形なのでこれをcpしてやればOKです。

cd ~/.composer/vendor/squizlabs/php_codesniffer/
cp CodeSniffer.conf.dist CodeSniffer.conf

コーディングルールのカスタマイズ

CodeSniffer.conf

<?php
 $phpCodeSnifferConfig = array (
  'default_standard' => 'PSR2',
  'report_format' => 'summary',
  'show_warnings' => '0',
  'show_progress' => '1',
  'report_width' => '120',
)
?>

例:以下の仕様で変更します。

report_format

summary -> full

summaryだと判定結果しか表示しないので、どこが問題かを表示するためにfullを設定します。

show_warnings

0 -> 1

警告も表示するように変更します。(鬱陶しければ0でもOK)

動作確認

判定するソースコード

test.php

<?php
/**
 * Test Code
 */
$is_echo = true;
echo_phpcs($is_echo);
function echo_phpcs($is_echo) {
    if ( $is_echo ) { 
        echo "hello php_codesniffer!!\n";
    }   
}

判定

$ ~/.composer/vendor/bin/phpcs -s test.php
E 1 / 1 (100%)
FILE: test.php
------------------------------------------------------------------------------------------------------------------------
FOUND 3 ERRORS AND 1 WARNING AFFECTING 3 LINES
------------------------------------------------------------------------------------------------------------------------
  1 | WARNING | [ ] A file should declare new symbols (classes, functions, constants, etc.) and cause no other side
    |         |     effects, or it should execute logic with side effects, but should not do both. The first symbol is
    |         |     defined on line 9 and the first side effect is on line 5.
    |         |     (PSR1.Files.SideEffects.FoundWithSymbols)
  9 | ERROR   | [x] Opening brace should be on a new line
    |         |     (Squiz.Functions.MultiLineFunctionDeclaration.BraceOnSameLine)
 10 | ERROR   | [x] Expected 0 spaces after opening bracket; 1 found
    |         |     (PSR2.ControlStructures.ControlStructureSpacing.SpacingAfterOpenBrace)
 10 | ERROR   | [x] Expected 0 spaces before closing bracket; 1 found
    |         |     (PSR2.ControlStructures.ControlStructureSpacing.SpaceBeforeCloseBrace)
------------------------------------------------------------------------------------------------------------------------
PHPCBF CAN FIX THE 3 MARKED SNIFF VIOLATIONS AUTOMATICALLY
------------------------------------------------------------------------------------------------------------------------
Time: 81ms; Memory: 6MB

-sをつけて実行すると、エラーとなったルールのキーを教えてくれます。

例:(PSR1.Files.SideEffects.FoundWithSymbols)

上のソースコードの例ではif文の括弧の内側の両サイドにスペースが入っているのでこれを消したい。しかし関数開始の波括弧 ( { ) で改行させたくない、というときには次のカスタムルールを使う。

カスタムルール

設定

以下のXMLファイルを作成します。

~/.composer/vendor/squizlabs/php_codesniffer/CodeSniffer/Standards/{ルール名}/ruleset.xml

ruleset.xml

<?xml version="1.0"?>
<ruleset name="MyStandard">
    <description>ほげほげ会社のコーディング規約</description>
    <rule ref="PSR2">
        <exclude name="Squiz.Functions.MultiLineFunctionDeclaration.BraceOnSameLine" />
    </rule>
</ruleset>

この場合、PSR2のコーディング規約を元に、関数の開始括弧のエラー(BraceOnSameLine)を許容します。(開始括弧で改行しなくてもいいよ、という設定)

判定

standardオプションに追加したルールを指定して実行します。

$ ~/.composer/vendor/bin/phpcs --standard=MyStandard -s test.php
E 1 / 1 (100%)
FILE: test.php
------------------------------------------------------------------------------------------------------------------------
FOUND 2 ERRORS AND 1 WARNING AFFECTING 2 LINES
------------------------------------------------------------------------------------------------------------------------
  1 | WARNING | [ ] A file should declare new symbols (classes, functions, constants, etc.) and cause no other side
    |         |     effects, or it should execute logic with side effects, but should not do both. The first symbol is
    |         |     defined on line 9 and the first side effect is on line 5.
    |         |     (PSR1.Files.SideEffects.FoundWithSymbols)
 10 | ERROR   | [x] Expected 0 spaces after opening bracket; 1 found
    |         |     (PSR2.ControlStructures.ControlStructureSpacing.SpacingAfterOpenBrace)
 10 | ERROR   | [x] Expected 0 spaces before closing bracket; 1 found
    |         |     (PSR2.ControlStructures.ControlStructureSpacing.SpaceBeforeCloseBrace)
------------------------------------------------------------------------------------------------------------------------
PHPCBF CAN FIX THE 2 MARKED SNIFF VIOLATIONS AUTOMATICALLY
------------------------------------------------------------------------------------------------------------------------
Time: 58ms; Memory: 6MB

phpcbfによりカスタムルールに沿った整形をする

phpcbfでも同じようにstandardオプションを指定します。

$ ~/.composer/vendor/bin/phpcbf --standard=MyStandard -s test.php
F 1 / 1 (100%)
PHPCBF RESULT SUMMARY
----------------------------------------------------------------------
FILE                                                  FIXED  REMAINING
----------------------------------------------------------------------
./phpcs/test.php                                      2      1
----------------------------------------------------------------------
A TOTAL OF 2 ERRORS WERE FIXED IN 1 FILE
----------------------------------------------------------------------
Time: 63ms; Memory: 6MB

if文の括弧の内側スペースのみが修正されています。

(関数の開始括弧で改行しなくてもよくなりました。)

<?php
/**
 * Test Code
 */
$is_echo = true;
echo_phpcs($is_echo);
function echo_phpcs($is_echo) {
    if ($is_echo) {
        echo "hello php_codesniffer!!\n";
    }   
}

※CodeSniffer.confのdefault_standardにカスタムルールを設定しておけば、いちいちオプション指定しなくてすむようにできます。

コメント

  1. All the games you can play on the Sega Genesis - AprCasino
    The best part is, worrione.com of course, the game, is that there are very few people who do a lot www.jtmhub.com of https://septcasino.com/review/merit-casino/ the 바카라 사이트 hard work. The best part is, apr casino if the

    返信削除

コメントを投稿

このブログの人気の投稿

docker-compose up で proxyconnect tcp: dial tcp: lookup proxy.example.com: no such host

docker-compose で起動したweb、MySQLに接続できない事象