You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何修复PHPStan提示的PendingRequest::get()参数类型不匹配错误?

修复PHPStan提示的PendingRequest::get()参数类型不匹配问题

PHPStan报错是因为$fileResponse->url的类型为string|null,而Illuminate\Http\Client\PendingRequest::get()要求第一个参数必须是string类型。以下是几种可行的修复方案:

方案1:检查URL有效性,不存在则抛出异常

这是最健壮的方案——如果Stripe返回的文件没有URL,后续获取文件内容的逻辑根本无法执行,直接抛出异常能快速定位问题:

public function generate(GetFileData $data): Response
{
    /** @var File $fileResponse */
    $fileResponse = stripe()->files->retrieve(
        $data->file_ref
    );

    $mimetype = $fileResponse->type ? $this->getMimeType($fileResponse->type) : 'text/csv';
    $authKey = base64_encode(Str::ascii(config('stripe.keys.secret')));
    
    // 检查URL是否存在
    $url = $fileResponse->url;
    if (!$url) {
        throw new \RuntimeException('无法获取文件的有效URL');
    }

    $response = Http::withHeaders([
        'Authorization' => 'Basic '.$authKey,
    ])->get($url);

    return response($response->body())->header('content-type', $mimetype);
}

方案2:使用类型断言告知PHPStan

如果你能确定Stripe返回的File对象一定包含非空的url字段,可以通过类型断言让PHPStan忽略null警告:

public function generate(GetFileData $data): Response
{
    /** @var File $fileResponse */
    $fileResponse = stripe()->files->retrieve(
        $data->file_ref
    );

    $mimetype = $fileResponse->type ? $this->getMimeType($fileResponse->type) : 'text/csv';
    $authKey = base64_encode(Str::ascii(config('stripe.keys.secret')));
    
    // 断言url为string类型
    /** @var string $url */
    $url = $fileResponse->url;

    $response = Http::withHeaders([
        'Authorization' => 'Basic '.$authKey,
    ])->get($url);

    return response($response->body())->header('content-type', $mimetype);
}

方案3:提供默认值(不推荐)

可以用null合并运算符给url设置默认值,但如果默认值是空字符串,HTTP请求会失败,仅适合有 fallback 逻辑的场景:

$response = Http::withHeaders([
    'Authorization' => 'Basic '.$authKey,
])->get($fileResponse->url ?? '');

推荐方案

优先选择方案1,它兼顾了类型安全和运行时的错误处理,避免因URL缺失导致的隐性问题。

内容的提问来源于stack exchange,提问作者Zabs

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.30 10:50:58