phpstan を使っていて、trait に書いたタイプヒントが効かない。
composer.json
{
"name": "local/phpstan-test",
"autoload": {
"psr-4": {
"": "src/"
}
},
"require-dev": {
"php": ">=7.2",
"phpstan/phpstan": "^0.12"
}
}
composer install
src/FooTrait.php
<?php
trait FooTrait
{
/**
* @param mixed $data
*/
public function traitMethod($data): int
{
return 0;
}
}
src/Foo.php
<?php
class Foo
{
use FooTrait;
public function run(): int
{
return $this->traitMethod("foo");
}
}
vendor/bin/phpstan analyze -l8 src/
2/2 [▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓] 100%
[OK] No errors
初回はOK。
ここでコメントを追加する。
src/FooTrait.php
<?php
trait FooTrait
{
/**
* @param mixed $data
* @return int
*/
public function traitMethod($data): int
{
return 0;
}
}
php7.2 vendor/bin/phpstan analyze -l8 src/
2/2 [▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓] 100%
------ ----------------------------------------------------------------
Line FooTrait.php (in context of class Foo)
------ ----------------------------------------------------------------
9 Method Foo::traitMethod() has parameter $data with no typehint
specified.
------ ----------------------------------------------------------------
[ERROR] Found 1 error
そうするとエラーになる。
@param $data
はそのままなのにエラーが出るのでハマった。
rm -rf /tmp/phpstan
vendor/bin/phpstan analyze -l8 src/
2/2 [▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓] 100%
[OK] No errors
キャッシュを消すとOKになる。
https://github.com/phpstan/phpstan/issues/1601
https://github.com/phpstan/phpstan/issues/1294#issuecomment-436951553
issue解消待ち。