php PHP_CodeSnifferを使用して構文チェックを行う

  • 作成日 2020.08.24
  • php
php PHP_CodeSnifferを使用して構文チェックを行う

windows10環境にPHP_CodeSnifferを使用して構文チェックを行う手順を記述してます。

環境

  • OS windows10 pro 64bit
  • Apache 2.4.43
  • PHP 7.4.5
  • Composer 1.10.5

※windows10にApacheのインストールはこちら
※windows10にphpのインストールはこちら
※Windows10にComposerのインストールはこちら

PHP_CodeSnifferインストール

composerを使用してインストールします。

composer global require "squizlabs/php_codesniffer=*"

バージョンを確認します。

phpcs --version

<出力結果>
PHP_CodeSniffer version 3.5.5 (stable) by Squiz (http://www.squiz.net)

PHP構文チェック

PHP_CodeSnifferを使用して構文チェックを行います。

ここでは下記のtest.phpの構文チェックを行います。

<?php
ini_set('display_errors', "On");
ini_set('mbstring.internal_encoding' , 'UTF-8');

function test(int $i){
    echo $i;
}
test(1)
?>

PSR2準拠で構文チェックを行うと、構文に問題のある箇所が表示されます。

phpcs --standard=PSR2 test.php

<出力結果>
----------------------------------------------------------------------
FOUND 5 ERRORS AND 1 WARNING AFFECTING 4 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 5 and the first side effect is
   |         |     on line 2.
 1 | ERROR   | [x] End of line character is invalid; expected "\n"
   |         |     but found "\r\n"
 3 | ERROR   | [x] Space found before comma in argument list
 5 | ERROR   | [x] Opening brace should be on a new line
 9 | ERROR   | [x] A closing tag is not permitted at the end of a PHP
   |         |     file
 9 | ERROR   | [x] Expected 1 newline at end of file; 0 found
----------------------------------------------------------------------
PHPCBF CAN FIX THE 5 MARKED SNIFF VIOLATIONS AUTOMATICALLY
----------------------------------------------------------------------

Time: 84ms; Memory: 6MB