How can PHPDoc comments be used with contracovariance return types?

39 views Asked by At

I have a table that stores encrypted json values for some sensitive data. The issue is that the json properties may alter slightly based on the type of record.

To overcome this, I created data transfer objects and then stored the class inside the database. The code works fine and a minified, reproduceable example is shown below:

interface IDto {}

class TestDto implements IDto
{
    public function __construct(public ?string $test = null) {}
}

function test(): ?IDto
{
    // TestDto::class is derived from the database
    $dto = new ReflectionClass(TestDto::class);

    if (in_array(IDto::class, $dto->getInterfaceNames()))
    {
        // Args dervice from the database after decrypting the json value and using json_decode
        return $dto->newInstanceArgs(['test' => 'foo']);
    }

    return null;
}

// Shows expected output, no issues
var_dump(test());

The problem is the IDE doesn't like that the return type is of an interface where as the newInstanceArgs() method returns an object.

I can overcome this with PHPDoc comments by first storing it into a variable and using a comment like so:

/** @var IDto $dtoInstance **/
$dtoInstance = $dto->newInstanceArgs(['test' => 'foo']);
return $dtoInstance;

However, this then makes the IDE want me to put it as an inline return statement which then puts me back to the same issue.

Is it possible to specify a PHPDoc comment to tell the IDE that the contraveriance is ok to ignore and the type will always be a IDto?

The IDE shows the following message (slightly changed namespace to fit to the example given above):

Return value is expected to be 'IDto|null', 'object' returned

0

There are 0 answers