VSCodeでphpcsを試してみる

WindowsPHPと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拡張機能のインストール

VSCodeでphpcsの拡張機能を入れる。
f:id:yk5656:20210211150731j:plain

[ファイル(F)]-[ユーザー設定]-[設定] (Ctrl+,)を開き、
[拡張機能]メニューの[PHP CodeSniffer]を選択し、
[settins.json で編集]を選ぶ。
f:id:yk5656:20210211150748j:plain

"phpcs.standard"に"phpcs.xml"を指定する。
f:id:yk5656:20210211150803j:plain

試しにチェックしてみる

適当に、test.phpと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では、規約に沿ってない箇所がエラーで表示される。 f:id:yk5656:20210211150815j:plain

今回は、改行コードがLFじゃないよ、と言っている。

ちなみに、チェックしたくないルールを除外する場合は、下記のような感じで書く。

<?xml version="1.0"?>
<ruleset name="hoge">
  <description>hogehoge</description>
  <rule ref="PSR2">
    <exclude name="Generic.Files.LineEndings" />
  </rule>
</ruleset>

こうすると除外される。 f:id:yk5656:20210211150831j:plain