概要
- Laravel8にPHPStanを導入したときのメモ
Larastanの選択
- PHPStanを直接入れるのではなく、Larastanを使うほうがスタンダードなのかと思い、Larastanを選択
Larastan 1.x
Laravel8以前は、Larastanの1系となる模様
ちなみにLaravel9移行がLarastanの2系となる
isntall
composer require nunomaduro/larastan:^1.0 --dev
上記コマンドのインストールが終わったら、*.neonファイルを作成する(手動で)
自動で作成されそうな記載もあるが、作成されなかった
touch phpstan.neon
公式のサンプルのneonファイルはテストに通らなかったので、少し加工して以下のように。
ignoreErrorsの部分で、エラーが出てしまったので、その部分は削除。
また、testsディレクトリを追加してみた
includes:
- ./vendor/nunomaduro/larastan/extension.neon
parameters:
paths:
- app
- tests
# The level 9 is the highest level
level: 0
excludePaths:
- ./vender
checkMissingIterableValueType: false
このように出ればOK
42/42 [▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓] 100% [OK] No errors
他のフォルダも追加
includes:
- ./vendor/nunomaduro/larastan/extension.neon
parameters:
paths:
- app
- config
- tests
- database
- routes
# The level 9 is the highest level
level: 0
excludePaths:
- ./vender
checkMissingIterableValueType: false
エラーが発生する
上記のneonファイルで実行するとエラーが発生してしまった。
どうやら、$thisの解決ができないよ、というような感じ。
------ --------------------------- Line routes/console.php ------ --------------------------- 18 Undefined variable: $this ------ ---------------------------
実際にエラーがでているroutes/console.phpファイルを見てみると
<?php use Illuminate\Foundation\Inspiring; use Illuminate\Support\Facades\Artisan; /* |-------------------------------------------------------------------------- | Console Routes |-------------------------------------------------------------------------- | | This file is where you may define all of your Closure based console | commands. Each Closure is bound to a command instance allowing a | simple approach to interacting with each command's IO methods. | */ Artisan::command('inspire', function () { $this->comment(Inspiring::quote()); })->purpose('Display an inspiring quote');
このようになっており、$thisがアカンらしい。
無視
解決できないようなので、無視するのがいいらしい
/* @phpstan-ignore-next-line */
このような感じでphpstanに無視を教えてあげることが可能(各種Linterと似たような感じ)
Artisan::command('inspire', function () {
/* @phpstan-ignore-next-line */
$this->comment(Inspiring::quote());
})->purpose('Display an inspiring quote');
上記のようになりました。