diff --git a/src/Type/TypeCombinator.php b/src/Type/TypeCombinator.php index dba57c908a2..cd08b5615f0 100644 --- a/src/Type/TypeCombinator.php +++ b/src/Type/TypeCombinator.php @@ -80,10 +80,11 @@ public static function clearCache(): void public static function addNull(Type $type): Type { - $nullType = new NullType(); - - if ($nullType->isSuperTypeOf($type)->no()) { - return self::union($type, $nullType); + // asking the type itself is both cheaper than NullType::isSuperTypeOf() + // (UnionType memoizes isNull(), isSubTypeOf() recomputes) and right for + // `never`, of which null is a supertype without never containing it. + if ($type->isNull()->no()) { + return self::union($type, new NullType()); } return $type; diff --git a/tests/PHPStan/Type/TypeCombinatorTest.php b/tests/PHPStan/Type/TypeCombinatorTest.php index 3f6b1db98ab..ad6dfe96a33 100644 --- a/tests/PHPStan/Type/TypeCombinatorTest.php +++ b/tests/PHPStan/Type/TypeCombinatorTest.php @@ -92,6 +92,16 @@ public static function dataAddNull(): array NullType::class, 'null', ], + [ + new NeverType(), + NullType::class, + 'null', + ], + [ + new NeverType(true), + NullType::class, + 'null', + ], [ new VoidType(), UnionType::class,