VSCodeでphpcsを試してみる
※WindowsにPHPとComposerはインストールされた状態。
php_codesnifferのインストール
php_codesnifferを入れる。
> composer global require squizlabs/php_codesniffer
インストールされている規約は下記の通り。
> phpcs -i The installed coding standards are MySource, PEAR, PSR1, PSR12, PSR2, Squiz and Zend
規約に定義されているルールは下記のように確認できる。 (下記は「PSR2」の場合)
> phpcs --standard=PSR2 -e The PSR2 standard contains 43 sniffs Generic (13 sniffs) ------------------- Generic.ControlStructures.InlineControlStructure Generic.Files.ByteOrderMark Generic.Files.LineEndings Generic.Files.LineLength Generic.Formatting.DisallowMultipleStatements Generic.Functions.FunctionCallArgumentSpacing Generic.NamingConventions.UpperCaseConstantName Generic.PHP.DisallowAlternativePHPTags Generic.PHP.DisallowShortOpenTag Generic.PHP.LowerCaseConstant Generic.PHP.LowerCaseKeyword Generic.WhiteSpace.DisallowTabIndent Generic.WhiteSpace.ScopeIndent PEAR (1 sniff) --------------- PEAR.Functions.ValidDefaultValue PSR1 (3 sniffs) --------------- PSR1.Classes.ClassDeclaration PSR1.Files.SideEffects PSR1.Methods.CamelCapsMethodName PSR2 (12 sniffs) ---------------- PSR2.Classes.ClassDeclaration PSR2.Classes.PropertyDeclaration PSR2.ControlStructures.ControlStructureSpacing PSR2.ControlStructures.ElseIfDeclaration PSR2.ControlStructures.SwitchDeclaration PSR2.Files.ClosingTag PSR2.Files.EndFileNewline PSR2.Methods.FunctionCallSignature PSR2.Methods.FunctionClosingBrace PSR2.Methods.MethodDeclaration PSR2.Namespaces.NamespaceDeclaration PSR2.Namespaces.UseDeclaration ・・・
VSCodeの拡張機能のインストール
[ファイル(F)]-[ユーザー設定]-[設定] (Ctrl+,)を開き、
[拡張機能]メニューの[PHP CodeSniffer]を選択し、
[settins.json で編集]を選ぶ。
"phpcs.standard"に"phpcs.xml"を指定する。
試しにチェックしてみる
phpcs.xml
<?xml version="1.0"?> <ruleset name="hoge"> <description>hogehoge</description> <rule ref="PSR2" /> </ruleset>
test.php
<?php echo "Hello, world!";
VSCodeでは、規約に沿ってない箇所がエラーで表示される。
今回は、改行コードがLFじゃないよ、と言っている。
ちなみに、チェックしたくないルールを除外する場合は、下記のような感じで書く。
<?xml version="1.0"?> <ruleset name="hoge"> <description>hogehoge</description> <rule ref="PSR2"> <exclude name="Generic.Files.LineEndings" /> </rule> </ruleset>
こうすると除外される。