[Php74] Skip cast (string) on ReflectionType on ChangeReflectionTypeToStringToGetNameRector (#510)

This commit is contained in:
Abdul Malik Ikhsan 2021-07-25 21:25:08 +07:00 committed by GitHub
parent cefa0d516b
commit ba990a2ec7
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
3 changed files with 48 additions and 4 deletions

View File

@ -74,8 +74,6 @@ return static function (ContainerConfigurator $containerConfigurator): void {
$parameters->set(Option::SKIP, [
// buggy in refactoring
AddSeeTestAnnotationRector::class,
// buggy in check ReflectionNamedType
ChangeReflectionTypeToStringToGetNameRector::class,
StringClassNameToClassConstantRector::class,
// some classes in config might not exist without dev dependencies

View File

@ -0,0 +1,20 @@
<?php
namespace Rector\Tests\Php74\Rector\MethodCall\ChangeReflectionTypeToStringToGetNameRector\Fixture;
use ReflectionMethod;
use ReflectionNamedType;
class SkipCastStringOnReflectionType
{
public function go(ReflectionMethod $reflectionMethod)
{
$returnType = $reflectionMethod->getReturnType();
return $returnType instanceof ReflectionNamedType
? $returnType->getName()
: (string) $returnType;
}
}
?>

View File

@ -12,6 +12,7 @@ use PhpParser\Node\Expr\Ternary;
use PhpParser\Node\Expr\Variable;
use PHPStan\Analyser\Scope;
use PHPStan\Type\ObjectType;
use PHPStan\Type\UnionType;
use Rector\Core\Rector\AbstractRector;
use Rector\NodeTypeResolver\Node\AttributeKey;
use Symplify\RuleDocGenerator\ValueObject\CodeSample\CodeSample;
@ -105,7 +106,32 @@ CODE_SAMPLE
if (! $this->isObjectType($node->expr, new ObjectType('ReflectionType'))) {
return null;
}
return $this->nodeFactory->createMethodCall($node->expr, self::GET_NAME);
$type = $this->nodeTypeResolver->resolve($node->expr);
if (! $type instanceof UnionType) {
return $this->nodeFactory->createMethodCall($node->expr, self::GET_NAME);
}
if (! $this->isWithReflectionType($type)) {
return $this->nodeFactory->createMethodCall($node->expr, self::GET_NAME);
}
return null;
}
private function isWithReflectionType(UnionType $unionType): bool
{
foreach ($unionType->getTypes() as $type) {
if (! $type instanceof ObjectType) {
continue;
}
if ($type->getClassName() !== 'ReflectionType') {
continue;
}
return true;
}
return false;
}
private function refactorMethodCall(MethodCall $methodCall): ?Node
@ -203,7 +229,7 @@ CODE_SAMPLE
return $this->isName($methodCall->name, 'getReturnType');
}
private function refactorReflectionFunctionGetReturnType(MethodCall $methodCall): Node
private function refactorReflectionFunctionGetReturnType(MethodCall $methodCall): Node | Ternary
{
$refactoredMethodCall = $this->refactorIfHasReturnTypeWasCalled($methodCall);
if ($refactoredMethodCall !== null) {