PHP_CodeSnifferでCakePHPのコーディング規約チェック
掲題の通り。メモ書き。ちなみに環境はCentOS6.4。
まずは、PHP_CodeSnifferをインストール。
[root@localhost hogehoge]# pear install PHP_CodeSniffer WARNING: channel "pear.php.net" has updated its protocols, use "pear channel-update pear.php.net" to update Unknown remote channel: pear.phpunit.de Did not download optional dependencies: channel://pear.phpunit.de/PHP_Timer, use --alldeps to download automatically pear/PHP_CodeSniffer can optionally use package "channel://pear.phpunit.de/PHP_Timer" downloading PHP_CodeSniffer-1.4.5.tgz ... Starting to download PHP_CodeSniffer-1.4.5.tgz (377,255 bytes) .................done: 377,255 bytes install ok: channel://pear.php.net/PHP_CodeSniffer-1.4.5
次に、phpcsを叩いて、フォローされている規約を確認。
[root@localhost hogehoge]# phpcs -i The installed coding standards are PSR1, MySource, Squiz, PEAR, PSR2, PHPCS and Zend
デフォルトではCakePHPの規約はフォローしていないので、以下のようにして、CakePHPの規約を追加。
[root@localhost hogehoge]# git clone https://github.com/cakephp/cakephp-codesniffer.git Initialized empty Git repository in *********/cakephp-codesniffer/.git/ remote: Counting objects: 606, done. remote: Compressing objects: 100% (370/370), done. remote: Total 606 (delta 264), reused 553 (delta 224) Receiving objects: 100% (606/606), 100.45 KiB | 110 KiB/s, done. Resolving deltas: 100% (264/264), done. [root@localhost hogehoge]# cp -R cakephp-codesniffer /usr/share/pear/PHP/CodeSniffer/Standards/CakePHP
再度、phpcsを叩いて、インストールされている規約の中にCakePHPが追加されたかを確認。
[root@localhost hogehoge]# phpcs -i The installed coding standards are PSR1, MySource, Squiz, CakePHP, PEAR, PSR2, PHPCS and Zend
CakePHPの規約が追加されたので、以下のような適当なサンプルコードを作って、簡単に動作確認。分かりにくいかもしれませんが、スペースでインデントしていますので、CakePHPの規約的にはNGな書き方です。
<?php echo 'test';
コードを設置したフォルダまで移動して、以下の通りに実行。エラーの旨がレポートされていますので、期待される動作としてはOKですね。
[root@localhost hogehoge]# phpcs --report=summary --report-checkstyle=phpcs.xml --standard=CakePHP --extensions=php . PHP CODE SNIFFER REPORT SUMMARY -------------------------------------------------------------------------------- FILE ERRORS WARNINGS -------------------------------------------------------------------------------- ************/test.php 1 0 -------------------------------------------------------------------------------- A TOTAL OF 1 ERROR(S) AND 0 WARNING(S) WERE FOUND IN 1 FILE(S) --------------------------------------------------------------------------------
ちなみに、実行したフォルダの中にphpcs.xmlが生成されるので、その中を覗くと、「インデントはタブを使えや、鬱陶しいのう。スペースは使うなよ!」と出力されています。
[root@localhost hogehoge]# cat phpcs.xml <?xml version="1.0" encoding="UTF-8"?> <checkstyle version="1.4.5"> <file name="************/test.php"> <error line="2" column="1" severity="error" message="Tabs must be used to indent lines; spaces are not allowed" source="Generic.WhiteSpace.DisallowSpaceIndent.TabsUsed"/> </file> </checkstyle>
参考:
http://masutaka.net/chalow/2011-12-30-3.html
以上