phpstan 中的 @template 在 laravel CastsAttributes 中不太明白怎么用

1. 运行环境

1). 当前使用的 Laravel 版本?

9.x

2). 当前使用的 php/php-fpm 版本?

PHP 版本:最新

3). 业务环境

执行命令 phpstan analyse --memory-limit=-1

2. 问题描述?

namespace Illuminate\Contracts\Database\Eloquent;

/**
 * @template TGet
 * @template TSet
 */
interface CastsAttributes
{
    /**
     * Transform the attribute from the underlying model values.
     *
     * @param  \Illuminate\Database\Eloquent\Model  $model
     * @param  string  $key
     * @param  mixed  $value
     * @param  array  $attributes
     * @return TGet|null
     */
    public function get($model, string $key, $value, array $attributes);

    /**
     * Transform the attribute to its underlying model values.
     *
     * @param  \Illuminate\Database\Eloquent\Model  $model
     * @param  string  $key
     * @param  TSet|null  $value
     * @param  array  $attributes
     * @return mixed
     */
    public function set($model, string $key, $value, array $attributes);
}
namespace App\Casts;

use Illuminate\Contracts\Database\Eloquent\CastsAttributes;
use Illuminate\Database\Eloquent\Model;

abstract class AbstractCastsAttributes implements CastsAttributes
{
    protected int $defaultKey = -1;

    protected string $defaultValue = '未配置';

    /**
     * @var array<int|string, string>
     */
    protected array $items = [-1 => '未设置'];

    /**
     * Cast the given value.
     *
     * @param  Model  $model
     * @param  string  $value
     * @param  array<string, mixed>  $attributes
     */
    public function get($model, string $key, $value, array $attributes): string
    {
        if (is_numeric($value)) {
            return $this->items[$value] ?? $this->defaultValue;
        }

        return $value;
    }

    /**
     * Prepare the given value for storage.
     *
     * @param  Model  $model
     * @param  int|string  $value
     * @param  array<string, mixed>  $attributes
     */
    public function set($model, string $key, $value, array $attributes): int
    {
        if (isset($this->items[$value])) {
            return (int) $value;
        }

        if (method_exists($this, 'format')) {
            $value = $this->format($value);
        }

        if (($k = array_search($value, $this->items, true)) === false) {
            return $this->defaultKey;
        }

        return (int) $k;
    }
}

3. 您期望得到的结果?

phpstan 不报错

4. 您实际得到的结果?

phpstan 中的 @template 在 laravel  CastsAttributes 中不太明白怎么用

报错: Class App\Casts\AbstractCastsAttributes implements generic interface Illuminate\Contracts\Database\Eloquent\CastsAttributes but does not specify its types: TGet, TSet

看了文档,单函数的 template 明白怎么用了,implements interface 不明白怎么使用

世界上最遥远的距离不是生与死,而是你亲手制造的BUG就在你眼前,你却怎么都找不到ta。
《L05 电商实战》
从零开发一个电商项目,功能包括电商后台、商品 & SKU 管理、购物车、订单管理、支付宝支付、微信支付、订单退款流程、优惠券等
《L02 从零构建论坛系统》
以构建论坛项目 LaraBBS 为线索,展开对 Laravel 框架的全面学习。应用程序架构思路贴近 Laravel 框架的设计哲学。
讨论数量: 3
5个月前 评论
kis龍 (楼主) 5个月前
Rache1 (作者) 5个月前

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