Skip to content

Commit 36c797c

Browse files
vojtech-dobesstaabm
authored andcommitted
Fix containsNull() for union with (null&T of mixed)
1 parent 5d0e250 commit 36c797c

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
@@ -1653,7 +1653,7 @@ parameters:
16531653
-
16541654
rawMessage: 'Doing instanceof PHPStan\Type\NullType is error-prone and deprecated. Use Type::isNull() instead.'
16551655
identifier: phpstanApi.instanceofType
1656-
count: 2
1656+
count: 1
16571657
path: src/Type/TypeCombinator.php
16581658

16591659
-

‎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
@@ -1873,6 +1873,15 @@ public function testNullSafe(): void
18731873
]);
18741874
}
18751875

1876+
public function testNullSafeOnTemplateTypeNarrowedAgainstNull(): void
1877+
{
1878+
$this->checkThisOnly = false;
1879+
$this->checkNullables = true;
1880+
$this->checkUnionTypes = true;
1881+
1882+
$this->analyse([__DIR__ . '/data/nullsafe-method-call-template-type.php'], []);
1883+
}
1884+
18761885
#[RequiresPhp('< 8.0.0')]
18771886
public function testDisallowNamedArguments(): void
18781887
{
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)