Skip to content

PHPStan confuses same-name template types defined in different classes #4557

@morozov

Description

@morozov

Bug report

If a template type with the same name is used in two classes, one of which calls a method of the other, PHPStan confuses the type constraint that should be applied to the argument used in a call.

The issue is currently reproducible on doctrine/dbal#4501 but I cannot reproduce it in the playground.

Code snippet that reproduces the problem

<?php

declare(strict_types=1);

namespace Doctrine\DBAL\Tests\Platforms;

use Doctrine\DBAL\Platforms\AbstractPlatform;
use PHPUnit\Framework\TestCase;

/**
 * @template T of AbstractPlatform
 */
abstract class AbstractPlatformTestCase extends TestCase
{
    public function testGetCreateTableSqlDispatchEvent(): void
    {
        $listenerMock = $this->createMock(GetCreateTableSqlDispatchEventListener::class);
    }
}

interface GetCreateTableSqlDispatchEventListener
{
}

Expected output

No issue.

Actual output

$ phpstan a tests/Platforms/AbstractPlatformTestCase.php
Note: Using configuration file /home/morozov/Projects/dbal/phpstan.neon.dist.
 1/1 [▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓] 100%

 ------ ------------------------------------------------------------------------------------ 
  Line   AbstractPlatformTestCase.php                                                        
 ------ ------------------------------------------------------------------------------------ 
  17     Parameter #1 $originalClassName of method PHPUnit\Framework\TestCase::createMock()  
         expects class-string<T of Doctrine\DBAL\Platforms\AbstractPlatform>, string given.  
  17     Unable to resolve the template type T in call to method                             
         PHPUnit\Framework\TestCase::createMock()                                            
         💡 See:                                                                              
         https://phpstan.org/blog/solving-phpstan-error-unable-to-resolve-template-type      
 ------ ------------------------------------------------------------------------------------ 

                                                                                                
 [ERROR] Found 2 errors                                                                         

If I rename the template type T to something else (e.g. Z), the problem disappears.

Even if the problem is in the code, the error message is misleading:

Parameter #​1 $originalClassName of method PHPUnit\Framework\TestCase::createMock() expects class-string<T of Doctrine\DBAL\Platforms\AbstractPlatform>.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions