[PHPStanStaticTypeMapper] Add closure conversion (#5043)

This commit is contained in:
Tomas Votruba 2020-12-29 22:22:48 +01:00 committed by GitHub
parent 81751880b2
commit 6ddb4effd8
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 64 additions and 3 deletions

View File

@ -7,14 +7,22 @@ namespace Rector\PHPStanStaticTypeMapper\TypeMapper;
use Closure;
use PhpParser\Node;
use PhpParser\Node\Name;
use PHPStan\PhpDocParser\Ast\Type\IdentifierTypeNode;
use PHPStan\PhpDocParser\Ast\Type\TypeNode;
use PHPStan\Type\ClosureType;
use PHPStan\Type\Type;
use Rector\Core\Exception\NotImplementedException;
use Rector\AttributeAwarePhpDoc\Ast\Type\AttributeAwareCallableTypeNode;
use Rector\PHPStanStaticTypeMapper\Contract\PHPStanStaticTypeMapperAwareInterface;
use Rector\PHPStanStaticTypeMapper\Contract\TypeMapperInterface;
use Rector\PHPStanStaticTypeMapper\PHPStanStaticTypeMapper;
final class ClosureTypeMapper implements TypeMapperInterface
final class ClosureTypeMapper implements TypeMapperInterface, PHPStanStaticTypeMapperAwareInterface
{
/**
* @var PHPStanStaticTypeMapper
*/
private $phpStanStaticTypeMapper;
public function getNodeClass(): string
{
return ClosureType::class;
@ -25,7 +33,11 @@ final class ClosureTypeMapper implements TypeMapperInterface
*/
public function mapToPHPStanPhpDocTypeNode(Type $type): TypeNode
{
throw new NotImplementedException();
$identifierTypeNode = new IdentifierTypeNode($type->getClassName());
$returnDocTypeNode = $this->phpStanStaticTypeMapper->mapToPHPStanPhpDocTypeNode($type->getReturnType());
return new AttributeAwareCallableTypeNode($identifierTypeNode, [], $returnDocTypeNode);
}
/**
@ -44,4 +56,9 @@ final class ClosureTypeMapper implements TypeMapperInterface
{
return '\\' . Closure::class;
}
public function setPHPStanStaticTypeMapper(PHPStanStaticTypeMapper $phpStanStaticTypeMapper): void
{
$this->phpStanStaticTypeMapper = $phpStanStaticTypeMapper;
}
}

View File

@ -0,0 +1,44 @@
<?php
namespace Rector\TypeDeclaration\Tests\Rector\ClassMethod\AddArrayReturnDocTypeRector\Fixture;
/**
* @var string $description
*/
class ReturnArrayClosure
{
public function fields(): array
{
return [
'description' => function() {
return $this->description;
},
];
}
}
?>
-----
<?php
namespace Rector\TypeDeclaration\Tests\Rector\ClassMethod\AddArrayReturnDocTypeRector\Fixture;
/**
* @var string $description
*/
class ReturnArrayClosure
{
/**
* @return array<string, Closure>
*/
public function fields(): array
{
return [
'description' => function() {
return $this->description;
},
];
}
}
?>