skip to Main Content

I am using PHPStan for static analysis on a PHP application, I have this set quite high which can be problematic at times and i’m getting the following error.

    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')));
        $response = Http::withHeaders([
            'Authorization' => 'Basic '.$authKey,
        ])->get($fileResponse->url);

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

    private function getMimeType(string $mimetype): string
    {
        $mimetypes = [
            'apk' => 'application/vnd.android.package-archive',
            'csv' => 'text/csv',
            'docx' => 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
            'gif' => 'image/gif',
            'html' => 'text/html',
            'jpeg' => 'image/jpeg',
            'json' => 'application/json',
            'jsonl' => 'application/jsonl',
            'markdown' => 'text/markdown',
            'pdf' => 'application/pdf',
            'png' => 'image/png',
            'svg' => 'image/svg+xml',
            'tiff' => 'image/tiff',
            'tsv' => 'text/tab-separated-values',
            'txt' => 'text/plain',
            'xlsl' => 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
            'xml' => 'application/xml',
            'zip' => 'application/zip',
        ];

        return $mimetypes[$mimetype];
    }

In the generate() I get the following phpstan error

  92     Parameter #1 $url of method IlluminateHttpClientPendingRequest::get() expects string, string|null given.  
 ------ ------------------------------------------------------------------------------------------------------------- 

How should I fix this?

2

Answers


  1. You either has to check $fileResponse->url is not null and handle it in code before you reach the get.

    Or if you are confident it will always be a string you could;

    /** @var string $url */
    $url = $fileResponse->url;
    $response = Http::withHeaders([
        'Authorization' => 'Basic '.$authKey,
    ])->get($url);
    
    Login or Signup to reply.
  2. Use one of the techniques described in Narrowing types https://phpstan.org/writing-php-code/narrowing-types to eliminate the possibility of the property value being null.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search