Is there any way of using an object type in @property-read and "declare" its attributes?

Viewed 106

I want to add a type of object in @property-read and also be able to access its attributes with PhpStorm suggestions.

Here's what I would like to do:

/**
* @property-read object{type: string, schema: string} $request_schema
* @property-read object{type: string, schema: string} $response_schema
*/
class ConfigApiRoutesSchema extends BaseSchema
{
...
}

The reason I'm doing this is because I want to access the attributes type and schema, like this:

$configApiRoutesSchema = new ConfigApiRoutesSchema();
$configApiRoutesSchema->request_schema->type // Here's the problem, type is not suggested
$configApiRoutesSchema->request_schema->schema // schema is also not suggested

This is exactly what I need, but unfortunately this doesn't work for some reason. One solution is to create two classes and specify them as types:

/**
* @property-read string $type
* @property-read string $schema
*/
class RequestSchema {}
    
/**
* @property-read string $type
* @property-read string $schema
*/
class ResponseSchema {}
    

    
/**
* @property-read RequestSchema $request_schema
* @property-read ResponseSchema $response_schema
* @
*/
class ConfigApiRoutesSchema extends BaseSchema {}

Now PhpStorm suggests both schema and type.

But it doesn't seem correct, since RequestSchema and ResponseSchema won't actually be used. So I wonder if there's any way of using annotation with objects without having to create a class to suggest its attributes.

Thank you.

1 Answers

Altho it is possible to specify the shape of arrays, for objects it is not possible to do so (yet). Such a syntax would have been be specified in PSR-5 and PSR-19, but this is not the case.

In the same manner it is not possible to specify the properties of a returned plain object from a method with the @return object annotion.

Apparently the syntax is supported by Psalm, but not in PhpStorm (at very least not yet).

Currently there is a public proposal on the PhpStorm YouTrack board. You might want to upvote that issue to increase it's chance of being included in the next PhpStorm version.

Related