hysryt / wiki

https://hysryt.github.io/wiki/
0 stars 0 forks source link

PHP_CodeSniffer #159

Open hysryt opened 3 years ago

hysryt commented 3 years ago

https://github.com/squizlabs/PHP_CodeSniffer

hysryt commented 3 years ago

コーディングルールを設定し、違反の検出と自動修正を行うツール。 違反の検出はphpcs、自動修正は phpcbf でそれぞれ行う。

composer install --dev squizlabs/php_codesniffer

コーディングルールは phpcs.xml に記述する。

phpcs.xml 例

<?xml version="1.0"?>
<ruleset>
    <rule ref="PSR12" />
    <file>.</file>
    <exclude-pattern type="relative">^vendor/*</exclude-pattern>
</ruleset>

上記の設定は以下の内容となる。 ・PSR12のルールに従う ・カレントディレクトリは以下の全てのファイルに対してチェックを行う ・ただし vender ディレクトリは除外する

composer.json に以下の設定をすることで composer check-cs で違反の検出、composer fix-cs で自動修正が行える。

composer.json

{
    "require-dev": {
        "squizlabs/php_codesniffer": "^3.5",
    },
    "scripts": {
        "check-cs": "@php ./vendor/squizlabs/php_codesniffer/bin/phpcs",
        "fix-cs": "@php ./vendor/squizlabs/php_codesniffer/bin/phpcbf"
    }
}
hysryt commented 3 years ago

WordPressコーディング規約の適用

composer require wp-coding-standards/wpcs

phpcs.xml

<?xml version="1.0"?>
<ruleset>
    <config name="installed_paths" value="vendor/wp-coding-standards/wpcs"/>

    <rule ref="WordPress" />
    <file>.</file>
    <exclude-pattern type="relative">^vendor/*</exclude-pattern>
</ruleset>
hysryt commented 3 years ago

git hooks

コミット前にステージングされたファイルを検証し、違反があればコミットを中断する

.git/hooks/pre-commit

echo $(git diff-index --cached --name-only HEAD) | composer check-cs
if [ $? -eq 0 ]; then
  exit 0
else
  exit 1
fi
hysryt commented 3 years ago

部分的な検証の無効化

class Test {
    // phpcs:disable
    private $a;
    // phpcs:enable
}
// phpcs:disable

から

// phpcs:enable

までの間の行は検証が行われない。

また、

//phpcs:ignore

の次の行だけは検証が行われない。