Skip to content

Support for @template-contravariant tag #7502

@oprypkhantc

Description

@oprypkhantc

Feature request

PHPStan currently allows two types of variance for template types in class-likes: @template (invariant) and @template-covariant (covariant). PHPStan also internally supports the third type: contravariant, but lacks support for specifying it for class-likes with a PHPDoc.

This is, however, sometimes useful:

/**
 * @template-contravariant T
 */
interface Comparator
{
    /**
      * @param T $e1
      * @param T $e2
      */
    public function compare($e1, $e2): int;
}

The implementation should theoretically be trivial: add support for @template-contravariant tag in phpdoc-parser, then correctly parse those tags into respective variance on phpstan side. As far as I understand, the support has been there internally for a long time already.

We'll also need to modify https://github.com/phpstan/phpstan-src/blob/f8be122188aa6721cec9872bd61676ee150a5311/src/Rules/Generics/VarianceCheck.php#L53 to check contravariance in parameters.

Did PHPStan help you today? Did it make you happy in any way?

PHPStan is awesome!

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions