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 时是如何解决这个问题的?

《L01 基础入门》
我们将带你从零开发一个项目并部署到线上,本课程教授 Web 开发中专业、实用的技能,如 Git 工作流、Laravel Mix 前端工作流等。
《L02 从零构建论坛系统》
以构建论坛项目 LaraBBS 为线索,展开对 Laravel 框架的全面学习。应用程序架构思路贴近 Laravel 框架的设计哲学。
最佳答案

写一条正则忽略错误就可以了。

1个月前 评论
sanders (楼主) 1个月前
讨论数量: 2

写一条正则忽略错误就可以了。

1个月前 评论
sanders (楼主) 1个月前

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!