phpstan l6报错 `Unable to resolve the template type`
环境
php:8.3.2
laravel:10.42.0
phpstan:1.10.63
larastan:2.9.2
当前问题
在使用 phpstan (level 6)进行静态分析时,报告如下错误:
------ --------------------------------------------------------------------------------------------------------------------------------------------
Line Services/Goods/BrandIndexService.php
------ --------------------------------------------------------------------------------------------------------------------------------------------
23 Unable to resolve the template type TWhenReturnType in call to method Illuminate\Database\Eloquent\Builder<App\Models\Goods\Brand>::when()
💡 See: https://phpstan.org/blog/solving-phpstan-error-unable-to-resolve-template-type
------ --------------------------------------------------------------------------------------------------------------------------------------------
出问题的代码如下:
<?php
namespace App\Services\Goods;
use App\Models\Goods\Brand;
use Illuminate\Database\Eloquent\Builder;
/**
* 品牌列表服务
*/
class BrandIndexService
{
/**
* 查询列表
*
* @param array<string,string> $options 查询参数
* @return Builder<Brand> 查询构建器
*/
public function handle(array $options = []): Builder
{
$keyword = $options['keyword'] ?? '';
return Brand::query()
->when($keyword, fn (Builder $query) => $query->likeName($keyword));
}
}
分析原因
我分析原因是模型查询构建器的 when()
方法中的 @template
注解导致:
/**
* Apply the callback if the given "value" is (or resolves to) truthy.
*
* @template TWhenParameter
* @template TWhenReturnType
*
* @param (\Closure($this): TWhenParameter)|TWhenParameter|null $value
* @param (callable($this, TWhenParameter): TWhenReturnType)|null $callback
* @param (callable($this, TWhenParameter): TWhenReturnType)|null $default
* @return $this|TWhenReturnType
*/
public function when($value = null, callable $callback = null, callable $default = null)
{
// ...
期望结果
希望能让 phpstan
在当前登记下,不报告这个错误,最好不要使用忽略注释,因为用到这个方法的地方会非常多。
请问大家在用 phpstan
时是如何解决这个问题的?
写一条正则忽略错误就可以了。