mirror of
https://github.com/rectorphp/rector.git
synced 2025-02-22 18:54:39 +01:00
add nullable type
This commit is contained in:
parent
3622daf00a
commit
a0397df9b7
@ -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, '?');
|
||||
}
|
||||
}
|
||||
|
@ -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);
|
||||
}
|
||||
|
@ -0,0 +1,10 @@
|
||||
<?php declare(strict_types=1);
|
||||
|
||||
namespace SomeNamespace;
|
||||
|
||||
class SomeClass
|
||||
{
|
||||
public function nullable() : ?\SomeType
|
||||
{
|
||||
}
|
||||
}
|
@ -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
|
||||
|
@ -0,0 +1,10 @@
|
||||
<?php declare(strict_types=1);
|
||||
|
||||
namespace SomeNamespace;
|
||||
|
||||
class SomeClass
|
||||
{
|
||||
public function nullable()
|
||||
{
|
||||
}
|
||||
}
|
@ -4,3 +4,4 @@ services:
|
||||
'SomeNamespace\SomeClass':
|
||||
'parse': 'array'
|
||||
'resolve': 'SomeType'
|
||||
'nullable': '?SomeType'
|
||||
|
Loading…
x
Reference in New Issue
Block a user