add nullable type

This commit is contained in:
Tomas Votruba 2018-04-25 20:09:09 +02:00
parent 3622daf00a
commit a0397df9b7
6 changed files with 33 additions and 0 deletions

View File

@ -2,10 +2,17 @@
namespace Rector\Php;
use Nette\Utils\Strings;
final class TypeAnalyzer
{
public function isPhpReservedType(string $type): bool
{
return in_array($type, ['string', 'bool', 'mixed', 'object', 'iterable', 'array'], true);
}
public function isNullableType(string $type): bool
{
return Strings::startsWith($type, '?');
}
}

View File

@ -5,6 +5,7 @@ namespace Rector\Rector\Dynamic;
use PhpParser\Node;
use PhpParser\Node\Identifier;
use PhpParser\Node\Name\FullyQualified;
use PhpParser\Node\NullableType;
use PhpParser\Node\Param;
use PhpParser\Node\Stmt\Class_;
use PhpParser\Node\Stmt\ClassLike;
@ -150,8 +151,11 @@ CODE_SAMPLE
return $classMethodNode;
}
// @todo possibly decouple to smth like IdentifierRenamer?
if ($this->typeAnalyzer->isPhpReservedType($newTypehint)) {
$classMethodNode->returnType = new Identifier($newTypehint);
} elseif ($this->typeAnalyzer->isNullableType($newTypehint)) {
$classMethodNode->returnType = new NullableType('\\' . ltrim($newTypehint, '?'));
} else {
$classMethodNode->returnType = new FullyQualified($newTypehint);
}

View File

@ -0,0 +1,10 @@
<?php declare(strict_types=1);
namespace SomeNamespace;
class SomeClass
{
public function nullable() : ?\SomeType
{
}
}

View File

@ -22,6 +22,7 @@ final class ReturnTypehintRectorTest extends AbstractRectorTestCase
{
yield [__DIR__ . '/Wrong/wrong.php.inc', __DIR__ . '/Correct/correct.php.inc'];
yield [__DIR__ . '/Wrong/wrong2.php.inc', __DIR__ . '/Correct/correct2.php.inc'];
yield [__DIR__ . '/Wrong/wrong3.php.inc', __DIR__ . '/Correct/correct3.php.inc'];
}
protected function provideConfig(): string

View File

@ -0,0 +1,10 @@
<?php declare(strict_types=1);
namespace SomeNamespace;
class SomeClass
{
public function nullable()
{
}
}

View File

@ -4,3 +4,4 @@ services:
'SomeNamespace\SomeClass':
'parse': 'array'
'resolve': 'SomeType'
'nullable': '?SomeType'