psr7 icon indicating copy to clipboard operation
psr7 copied to clipboard

Return `static` for MessageTrait `with...` methods

Open braindawg opened this issue 1 year ago • 0 comments

Description The with... methods on MessageTrait (e.g. withHeader()) currently return typehint a MessageInterface, which breaks static analysis if the analyzer is aware that the Guzzle implementation of PSR7 is being used.

Per the PSR-7 spec, these methods should all return typehint static.

Example

function emitEmptyResponse(EmitterInterface $emitter)
{
    $response = new \GuzzleHttp\Psr7\Response(body: json_encode([]));
    $emitter->emit($response->withHeader('Content-Type', 'json'));
}

This code generates a Psalm error at the emit() call, since the Emitter expects a ResponseInterface but the parent class MessageInterface is provided. I imagine PHPStan would have a similar issue, since the code is incorrect based on the return types currently specified.

Additional context PSR-7 spec for MessageInterface

This isn't a problem if the code is written well enough, since everything should depend on PSR interfaces like Psr\Http\Message\ResponseInterface (which does typehint static as the return for all these with methods) instead of library-specific PSR implementations, but I don't know what's gained by Guzzle explicitly typing these as MessageInterface.

braindawg avatar Oct 23 '24 17:10 braindawg