1

According to the CakePHP 4 docs

// If you want a json response
$response = $response->withType('application/json')
->withStringBody(json_encode(['Foo' => 'bar']));

If you run phpstan on level 7 it will give this error

Parameter #1 $string of method Cake\Http\Response::withStringBody() expects string|null, string|false given.

json_encode is a core PHP function which has return types string|false so can't be modified.

withStringBody() is a CakePHP core method which accepts string|null.

How can you get around that error since neither of those 2 things can be modified directly?

2
  • 2
    You could try casting the result of the function call to string (string)json_encode() Commented Aug 14, 2024 at 9:34
  • 2
    Do the json_encode first, on an earlier line, and if it returns false, don't pass it to withStringBody. If it does return false it indicates a problem with the encoding so I'd have thought you'd want to detect that and log an error and so on anyway. You can also set json-throw-on-error to make it automatically throw an exception when it fails, rather than having to detect it. Commented Aug 14, 2024 at 11:10

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.