如何修复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
相关产品推荐
相关产品推荐

