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. 您实际得到的结果?
报错: Class App\Casts\AbstractCastsAttributes implements generic interface Illuminate\Contracts\Database\Eloquent\CastsAttributes but does not specify its types: TGet, TSet
看了文档,单函数的 template 明白怎么用了,implements interface
不明白怎么使用
参考文档: