Skip to content

Return static for MessageTrait with... methods #617

@braindawg

Description

@braindawg

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.

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions