rector/src/PHPStanStaticTypeMapper/PHPStanStaticTypeMapper.php

55 lines
1.7 KiB
PHP
Raw Normal View History

<?php
declare (strict_types=1);
namespace Rector\PHPStanStaticTypeMapper;
use PhpParser\Node\ComplexType;
use PhpParser\Node\Identifier;
use PhpParser\Node\Name;
use PHPStan\PhpDocParser\Ast\Type\TypeNode;
use PHPStan\Type\Type;
use Rector\Exception\NotImplementedYetException;
use Rector\PHPStanStaticTypeMapper\Contract\TypeMapperInterface;
use Rector\PHPStanStaticTypeMapper\Enum\TypeKind;
use RectorPrefix202403\Webmozart\Assert\Assert;
final class PHPStanStaticTypeMapper
{
2020-01-14 17:59:15 +00:00
/**
* @var TypeMapperInterface[]
* @readonly
2020-01-14 17:59:15 +00:00
*/
private $typeMappers;
2020-01-14 17:59:15 +00:00
/**
* @param TypeMapperInterface[] $typeMappers
*/
public function __construct(array $typeMappers)
{
2020-01-14 17:59:15 +00:00
$this->typeMappers = $typeMappers;
Assert::notEmpty($typeMappers);
}
public function mapToPHPStanPhpDocTypeNode(Type $type) : TypeNode
{
2020-01-14 17:59:15 +00:00
foreach ($this->typeMappers as $typeMapper) {
if (!\is_a($type, $typeMapper->getNodeClass(), \true)) {
2020-01-14 17:59:15 +00:00
continue;
}
return $typeMapper->mapToPHPStanPhpDocTypeNode($type);
}
throw new NotImplementedYetException(__METHOD__ . ' for ' . \get_class($type));
}
/**
* @param TypeKind::* $typeKind
* @return \PhpParser\Node\Name|\PhpParser\Node\ComplexType|\PhpParser\Node\Identifier|null
*/
public function mapToPhpParserNode(Type $type, string $typeKind)
{
2020-01-14 17:59:15 +00:00
foreach ($this->typeMappers as $typeMapper) {
if (!\is_a($type, $typeMapper->getNodeClass(), \true)) {
2020-01-14 17:59:15 +00:00
continue;
}
return $typeMapper->mapToPhpParserNode($type, $typeKind);
}
throw new NotImplementedYetException(__METHOD__ . ' for ' . \get_class($type));
}
}