0

I'm using phpcs

When using code very similar to this(slightly altered for legal reasons):

function methodNameHere($desiredParameter){       
    $client = new Client([
        'base_uri' => 'confidential uri',
    ]);
   
    $headers = [
        'important-header' => 'confidential value'
    ];
    
    $request = new Request('GET', $desiredParameter, $headers);
    $response = $client->send($request, ['timeout' => 2]);

    if ($response->getStatusCode() != 200) {
        throw new BadResponseException('Oops! Bad request.', $request, $response);
    }

    $responseBody = $response->getBody()->getContents(); // String with the response body

    $paramInfo = json_decode($responseBody, true); // Associative array from response body

    return $paramInfo;

}

I get the following error:

 ERROR | [x] Useless variable $paramInfo.

pointing to the line where the variable $paramInfo is declared and initialized.

What am I doing wrong?

I tried reading the documentation for phpcs and slevomat but both are infuriatingly vague on this error. They just say something like "This means that this variable is useless" and don't actually explain what a useless variable is.

JB3
  • 15
  • 7
  • 2
    You're not doing anything "wrong", PHPCS just wants you to do `return json_decode(...);` directly. I.e., don't create a variable just to hold the thing you're about to return. Instead just return the thing. – Alex Howansky Dec 16 '22 at 18:18
  • Man, now I feel like a complete clown. Thanks for the solution @AlexHowansky . Would you mind moving it to an answer so I can accept it? – JB3 Dec 16 '22 at 18:28

1 Answers1

4

Here, $paramInfo is a useless variable:

$paramInfo = json_decode($responseBody, true);
return $paramInfo;

It's considered useless because it's unnecessary, it serves no purpose. It holds a value only as a placeholder for the subsequent return statement, and it will never be modified. Instead, just do this:

return json_decode($responseBody, true);

Alternatively, you could ignore this one warning:

// phpcs:ignore
$paramInfo = json_decode($responseBody, true);
return $paramInfo;
Alex Howansky
  • 50,515
  • 8
  • 78
  • 98