Skip to content

Typing support for grpc-php #33431

@TobiasGrether

Description

@TobiasGrether

Is your feature request related to a problem? Please describe.

I've recently started using the php-codegen for gRPC and it is really annoying that although the generator knows the return value of an rpc call, non-streaming rpc calls (with ->wait()) will just return an instance of UnaryCall. This might be fine for some, but PHP has been introducing more type safety and tools like PHPStan have become a must-have for many. It is quite annoying that there is no type-safety on the response of a grpc call at all.

Describe the solution you'd like

I'd like the UnaryCall class to extend PHPStans generic template system like the following:

/**
 * @template T of object
 * Represents an active call that sends a single message and then gets a
 * single response.
 */
class UnaryCall extends AbstractCall

with

    /**
     * Wait for the server to respond with data and a status.
     *
     * @return array{0: T, 1: any} [response data, status]
     */
    public function wait()
    {
        $batch = [
            OP_RECV_MESSAGE => true,
            OP_RECV_STATUS_ON_CLIENT => true,
        ];
        if ($this->metadata === null) {
            $batch[OP_RECV_INITIAL_METADATA] = true;
        }
        $event = $this->call->startBatch($batch);
        if ($this->metadata === null) {
            $this->metadata = $event->metadata;
        }
        $status = $event->status;
        $this->trailing_metadata = $status->metadata;

        return [$this->_deserializeResponse($event->message), $status];
    }

Instead of any for the status, one could also use a typed version of the Status data.
Now, what the generator could do is instead of just inserting

/**
 * @returns UnaryCall
 **/

it could instead return

/**
* @returns UnaryCall<my/simple/return/type>
**/

This should allow for IDEs like PHPStorm to detect the type of the response data, which would make development so much more intuitive.

This is just an example of where it could be implemented. This could be implemented in streaming-rpcs, server code and other places as well.

Describe alternatives you've considered

I have not come up with any good alternative to this suggestion yet.

Additional context

Metadata

Metadata

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions