Skip to content

Commit

Permalink
Resolve native return-type from native union-type in short ternary (#…
Browse files Browse the repository at this point in the history
…4606)

* Resolve native type from method call in short ternary

* Update ReturnTypeFromStrictTernaryRector.php

* fix class-name conflict

* Update return_from_ternary_phpdoc.php.inc

* fix

* Update skip_union_void.inc

* Update skip_union_void.inc

* more gracefull error handling

* Update rules/TypeDeclaration/Rector/Class_/ReturnTypeFromStrictTernaryRector.php

---------

Co-authored-by: Abdul Malik Ikhsan <samsonasik@gmail.com>
  • Loading branch information
staabm and samsonasik committed Jul 26, 2023
1 parent 729f03b commit c01925a
Show file tree
Hide file tree
Showing 3 changed files with 66 additions and 1 deletion.
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
<?php

namespace Rector\Tests\TypeDeclaration\Rector\Class_\ReturnTypeFromStrictTernaryRector\Fixture;

class Appointment
{
private function find_one(): self|false {
return false;
}

public function getRent()
{
$rent = $this->find_one();

return $rent ?: null;
}

}
?>
-----
<?php

namespace Rector\Tests\TypeDeclaration\Rector\Class_\ReturnTypeFromStrictTernaryRector\Fixture;

class Appointment
{
private function find_one(): self|false {
return false;
}

public function getRent(): ?\Rector\Tests\TypeDeclaration\Rector\Class_\ReturnTypeFromStrictTernaryRector\Fixture\Appointment
{
$rent = $this->find_one();

return $rent ?: null;
}

}
?>
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
<?php

namespace Rector\Tests\TypeDeclaration\Rector\Class_\ReturnTypeFromStrictTernaryRector\Fixture;

class SkipUnionVoid
{
private function find_one(): self|false {
return false;
}

public function getRent()
{
if (random_int(0 ,1 )) {
$rent = $this->find_one();

return $rent ?: null;
}
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@
use PHPStan\Type\UnionType;
use Rector\Core\Rector\AbstractScopeAwareRector;
use Rector\Core\ValueObject\PhpVersionFeature;
use Rector\NodeTypeResolver\Node\AttributeKey;
use Rector\PHPStanStaticTypeMapper\Enum\TypeKind;
use Rector\TypeDeclaration\TypeInferer\ReturnTypeInferer;
use Rector\VendorLocker\NodeVendorLocker\ClassMethodReturnTypeOverrideGuard;
Expand Down Expand Up @@ -95,7 +96,12 @@ public function refactorWithScope(Node $node, Scope $scope): ?Node

$ternary = $return->expr;

$nativeTernaryType = $scope->getNativeType($ternary);
$returnScope = $return->expr->getAttribute(AttributeKey::SCOPE);
if ($returnScope === null) {
return null;
}

$nativeTernaryType = $returnScope->getNativeType($ternary);
if ($nativeTernaryType instanceof MixedType) {
return null;
}
Expand Down

0 comments on commit c01925a

Please sign in to comment.