2020-09-06 00:04:49
PHPのコード静的解析ツール PHPStan を試してみた
PHPのコード静的解析ツール PHPStan を試してみた
バージョン情報
- XAMPP Control Panel v3.2.4
- PHP Version 7.4.9
- "phpstan/phpstan": "^0.12.42"
サンプルプロジェクトを作成
composer init
で任意のプロジェクトを作成します。 appclassessample.php
を作成します。今回はこのファイルを解析させます。
├─app
│ └─classes
│ └─sample.php # このファイルを解析してみる
└─vendor
sample.php
の中身です。
<?php
class Sample
{
function __construct($argument)
{
}
function sample_uncalled_method() {
echo "hello";
}
}
composer で PHPStan をインストール
https://phpstan.org/user-guide/getting-started に従ってインストールします。
composer require --dev phpstan/phpstan
実行する
app
ディレクトリ配下をレベル8で解析します。すると以下のエラーが検出されました。
- Sampleクラスの引数$argumentが未使用
- Sampleクラスの引数$argumentにタイプヒントが未設定
- Sampleクラスのメソッドsample_uncalled_method()の戻り値にタイプヒントが未設定
PS C:xampphtdocsstudy rylint> ./vendor/bin/phpstan analyse app --level 8
1/1 [============================] 100%
------ ----------------------------------------------------------------------------------
Line classessample.php
------ ----------------------------------------------------------------------------------
6 Constructor of class Sample has an unused parameter $argument.
6 Method Sample::__construct() has parameter $argument with no typehint specified.
11 Method Sample::sample_uncalled_method() has no return typehint specified.
------ ----------------------------------------------------------------------------------
[ERROR] Found 3 errors
PS C:xampphtdocsstudy rylint>
コードを修正して再度実行してみる
検出されたエラーをもとに sample.php
を以下に修正します。
<?php
class Sample
{
function __construct(string $argument)
{
echo $argument;
}
function sample_uncalled_method() :void {
echo "hello";
}
}
そして再度 PHPStan を実行した結果が以下です。先程検出されたエラーがなくなりました。
PS C:xampphtdocsstudy rylint> ./vendor/bin/phpstan analyse app --level 8
1/1 [============================] 100%
[OK] No errors
PS C:xampphtdocsstudy rylint>