rector/packages/PHPStanStaticTypeMapper/TypeMapper/ConditionalTypeMapper.php
Tomas Votruba 184cf49468 Updated Rector to commit f9de5d311e7e69d1ad2cb5f3087970d8b9335920
f9de5d311e [Php80] Handle RenameClassRector+AnnotationToAttributeRector with auto import and existing attribute defined (#5219)
2023-11-02 03:20:18 +00:00

65 lines
2.1 KiB
PHP

<?php
declare (strict_types=1);
namespace Rector\PHPStanStaticTypeMapper\TypeMapper;
use RectorPrefix202311\Nette\Utils\Strings;
use PhpParser\Node;
use PHPStan\PhpDocParser\Ast\Type\TypeNode;
use PHPStan\Reflection\ClassReflection;
use PHPStan\Type\ConditionalType;
use PHPStan\Type\ObjectType;
use PHPStan\Type\Type;
use PHPStan\Type\TypeCombinator;
use PHPStan\Type\TypeTraverser;
use Rector\PHPStanStaticTypeMapper\Contract\TypeMapperInterface;
use Rector\PHPStanStaticTypeMapper\Enum\TypeKind;
use Rector\PHPStanStaticTypeMapper\PHPStanStaticTypeMapper;
/**
* @implements TypeMapperInterface<ConditionalType>
*/
final class ConditionalTypeMapper implements TypeMapperInterface
{
/**
* @var \Rector\PHPStanStaticTypeMapper\PHPStanStaticTypeMapper
*/
private $phpStanStaticTypeMapper;
/**
* @api used in autowire, @todo add to lazy container or remove
*/
public function autowire(PHPStanStaticTypeMapper $phpStanStaticTypeMapper) : void
{
$this->phpStanStaticTypeMapper = $phpStanStaticTypeMapper;
}
/**
* @return class-string<Type>
*/
public function getNodeClass() : string
{
return ConditionalType::class;
}
/**
* @param ConditionalType $type
*/
public function mapToPHPStanPhpDocTypeNode(Type $type) : TypeNode
{
$type = TypeTraverser::map($type, static function (Type $type, callable $traverse) : Type {
if ($type instanceof ObjectType && !$type->getClassReflection() instanceof ClassReflection) {
$newClassName = (string) Strings::after($type->getClassName(), '\\', -1);
return $traverse(new ObjectType($newClassName));
}
return $traverse($type);
});
return $type->toPhpDocNode();
}
/**
* @param ConditionalType $type
* @param TypeKind::* $typeKind
*/
public function mapToPhpParserNode(Type $type, string $typeKind) : ?Node
{
$type = TypeCombinator::union($type->getIf(), $type->getElse());
return $this->phpStanStaticTypeMapper->mapToPhpParserNode($type, $typeKind);
}
}