[TypeDeclaration] Remove NullType when already has mixed on ParamAnnotationIncorrectNullableRector (#2081)

* [TypeDeclaration] Remove NullType when already has mixed on ParamAnnotationIncorrectNullableRector

* Fixed 🎉

* [ci-review] Rector Rectify

* final touch: clean up

* final touch: clean up

* final touch: eol

* final touch: clean up

* clean up

* final touch: clean up

Co-authored-by: GitHub Action <action@github.com>
This commit is contained in:
Abdul Malik Ikhsan 2022-04-16 23:09:12 +07:00 committed by GitHub
parent 91b8573525
commit 73bf29c279
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
3 changed files with 91 additions and 1 deletions

View File

@ -0,0 +1,33 @@
<?php
namespace Rector\Tests\TypeDeclaration\Rector\ClassMethod\ParamAnnotationIncorrectNullableRector\Fixture;
final class RemoveMixedWithNullable
{
/**
* @param mixed|null $default
*/
public function getEnvVar(string $var, mixed $default = null): mixed
{
return $this->env[$var] ?? $default;
}
}
?>
-----
<?php
namespace Rector\Tests\TypeDeclaration\Rector\ClassMethod\ParamAnnotationIncorrectNullableRector\Fixture;
final class RemoveMixedWithNullable
{
/**
* @param mixed $default
*/
public function getEnvVar(string $var, mixed $default = null): mixed
{
return $this->env[$var] ?? $default;
}
}
?>

View File

@ -0,0 +1,14 @@
<?php
namespace Rector\Tests\TypeDeclaration\Rector\ClassMethod\ParamAnnotationIncorrectNullableRector\Fixture;
final class SkipMixed
{
/**
* @param mixed $default
*/
public function getEnvVar(string $var, mixed $default = null): mixed
{
return $this->env[$var] ?? $default;
}
}

View File

@ -6,6 +6,7 @@ namespace Rector\TypeDeclaration\Helper;
use PhpParser\Node\Expr\ConstFetch;
use PhpParser\Node\Param;
use PHPStan\Type\MixedType;
use PHPStan\Type\NullType;
use PHPStan\Type\Type;
use PHPStan\Type\TypeCombinator;
@ -54,10 +55,52 @@ final class PhpDocNullableTypeHelper
$isPhpParserTypeContainingNullType = false;
}
return $this->resolveUpdatedPhpDocTypeFromPhpDocTypeAndPhpParserTypeNullInfo(
$resolvedType = $this->resolveUpdatedPhpDocTypeFromPhpDocTypeAndPhpParserTypeNullInfo(
$phpDocType,
$isPhpParserTypeContainingNullType
);
if ($resolvedType instanceof UnionType) {
return $this->cleanNullableMixed($resolvedType);
}
if ($resolvedType instanceof Type) {
return $resolvedType;
}
if (! $phpDocType instanceof UnionType) {
return null;
}
$cleanNullableMixed = $this->cleanNullableMixed($phpDocType);
if ($cleanNullableMixed === $phpDocType) {
return null;
}
return $cleanNullableMixed;
}
private function cleanNullableMixed(UnionType $unionType): Type
{
$types = $unionType->getTypes();
$isNullable = false;
$isMixed = false;
foreach ($types as $type) {
if ($type instanceof MixedType) {
$isMixed = true;
}
if ($type instanceof NullType) {
$isNullable = true;
}
}
if ($isMixed && $isNullable) {
return TypeCombinator::removeNull($unionType);
}
return $unionType;
}
private function isItRequiredToRemoveOrAddNullTypeToUnion(