Skip to content

Commit b307c46

Browse files
committed
Fix containsNull() for union with (null&T of mixed)
1 parent 951e5cb commit b307c46

4 files changed

Lines changed: 37 additions & 2 deletions

File tree

‎phpstan-baseline.neon‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1629,7 +1629,7 @@ parameters:
16291629
-
16301630
rawMessage: 'Doing instanceof PHPStan\Type\NullType is error-prone and deprecated. Use Type::isNull() instead.'
16311631
identifier: phpstanApi.instanceofType
1632-
count: 2
1632+
count: 1
16331633
path: src/Type/TypeCombinator.php
16341634

16351635
-

‎src/Type/TypeCombinator.php‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -175,7 +175,7 @@ public static function containsNull(Type $type): bool
175175
{
176176
if ($type instanceof UnionType) {
177177
foreach ($type->getTypes() as $innerType) {
178-
if ($innerType instanceof NullType) {
178+
if ($innerType->isNull()->yes()) {
179179
return true;
180180
}
181181
}

‎tests/PHPStan/Rules/Methods/CallMethodsRuleTest.php‎

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1890,6 +1890,15 @@ public function testNullSafe(): void
18901890
]);
18911891
}
18921892

1893+
public function testNullSafeOnTemplateTypeNarrowedAgainstNull(): void
1894+
{
1895+
$this->checkThisOnly = false;
1896+
$this->checkNullables = true;
1897+
$this->checkUnionTypes = true;
1898+
1899+
$this->analyse([__DIR__ . '/data/nullsafe-method-call-template-type.php'], []);
1900+
}
1901+
18931902
#[RequiresPhp('< 8.0.0')]
18941903
public function testDisallowNamedArguments(): void
18951904
{
Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
<?php // lint >= 8.0
2+
3+
namespace NullsafeMethodCallTemplateType;
4+
5+
class Foo
6+
{
7+
8+
public function getValue(): ?string
9+
{
10+
return null;
11+
}
12+
13+
}
14+
15+
/**
16+
* @template T
17+
* @param T $foo
18+
*/
19+
function foo($foo)
20+
{
21+
if ($foo !== null && !$foo instanceof Foo) {
22+
throw new \Exception();
23+
}
24+
25+
return $foo?->getValue();
26+
}

0 commit comments

Comments
 (0)