phpstan-doctrine icon indicating copy to clipboard operation
phpstan-doctrine copied to clipboard

fix: update template annotations to remove covariant keyword

Open deadLocks21 opened this issue 5 months ago • 0 comments

Description

This PR addresses PHPStan errors related to template type variance in Doctrine's metadata classes. The errors were occurring because the template type T was declared as covariant but was being used in an invariant position in the getReflectionClass() method.

The Problem

The following errors were reported by PHPStan:

  • Template type T is declared as covariant, but occurs in invariant position in return type of method Doctrine\ODM\MongoDB\Mapping\ClassMetadata::getReflectionClass()
  • Template type T is declared as covariant, but occurs in invariant position in return type of method Doctrine\ORM\Mapping\ClassMetadataInfo::getReflectionClass()
  • Template type T is declared as covariant, but occurs in invariant position in return type of method Doctrine\Persistence\Mapping\ClassMetadata::getReflectionClass()

The Solution

We removed the -covariant modifier from the template type declarations in:

  • MongoClassMetadataInfo.stub
  • ORM/Mapping/ClassMetadata.stub
  • ORM/Mapping/ClassMetadataInfo.stub
  • Persistence/Mapping/ClassMetadata.stub

Why This Works

The covariance modifier was inappropriate in this case because:

  1. The getReflectionClass() method returns a ReflectionClass<T>
  2. This return type must be exactly of the specified type, not a subtype or supertype
  3. When a type parameter is used in an invariant position (like a return type), it should not be declared as covariant

Issues

#646

deadLocks21 avatar Jun 03 '25 15:06 deadLocks21