Skip to content

Commit

Permalink
Fix AddMethodCallBasedStrictParamTypeRector for invalid generics type (
Browse files Browse the repository at this point in the history
  • Loading branch information
TomasVotruba committed Jan 13, 2023
1 parent fe7ed4f commit 774de56
Show file tree
Hide file tree
Showing 2 changed files with 56 additions and 2 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
<?php

declare(strict_types=1);

namespace Rector\Tests\TypeDeclaration\Rector\ClassMethod\AddMethodCallBasedStrictParamTypeRector\Fixture;

use Doctrine\ORM\EntityManagerInterface;
use PHPUnit\Framework\TestCase;
use Symfony\Component\DependencyInjection\Container;

final class SkipInvalidGenerics extends TestCase
{
private EntityManagerInterface $entityManager;

protected function setUp(): void
{
$this->entityManager = $this->get('entity_manager');
$this->initDatabase($this->entityManager);
}

/**
* @template TObject as object
*
* @param class-string<TObject> $type
* @return TObject
*/
public function get(string $type): object
{
$container = $this->getContainer();
return $container->get($type);
}

private function initDatabase(EntityManagerInterface $entityManager)
{
}

private function getContainer(): Container
{
return new Container();
}
}
17 changes: 15 additions & 2 deletions rules/TypeDeclaration/NodeAnalyzer/CallTypesResolver.php
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
use PhpParser\Node\Arg;
use PhpParser\Node\Expr\MethodCall;
use PhpParser\Node\Expr\StaticCall;
use PHPStan\Reflection\ReflectionProvider;
use PHPStan\Type\MixedType;
use PHPStan\Type\NullType;
use PHPStan\Type\ObjectType;
Expand All @@ -22,7 +23,8 @@ final class CallTypesResolver
{
public function __construct(
private readonly NodeTypeResolver $nodeTypeResolver,
private readonly TypeFactory $typeFactory
private readonly TypeFactory $typeFactory,
private readonly ReflectionProvider $reflectionProvider,
) {
}

Expand Down Expand Up @@ -57,7 +59,18 @@ private function resolveStrictArgValueType(Arg $arg): Type
$argValueType = $this->nodeTypeResolver->getNativeType($arg->value);

// "self" in another object is not correct, this make it independent
return $this->correctSelfType($argValueType);
$argValueType = $this->correctSelfType($argValueType);

if (! $argValueType instanceof ObjectType) {
return $argValueType;
}

// fix false positive generic type on string
if (! $this->reflectionProvider->hasClass($argValueType->getClassName())) {
return new MixedType();
}

return $argValueType;
}

private function correctSelfType(Type $argValueType): Type
Expand Down

0 comments on commit 774de56

Please sign in to comment.