Skip to content

Commit 1f10747

Browse files
committed
More precise MixedType::toBoolean() with subtracted type
1 parent 30e8e8b commit 1f10747

File tree

3 files changed

+24
-2
lines changed

3 files changed

+24
-2
lines changed

num.php

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
<?php
2+
3+
use function PHPStan\Testing\assertType;
4+
5+
/**
6+
* @param array<int, string> $arr
7+
*/
8+
function narrowKey($mixed, string $s, int $i, array $generalArr, array $arr): void {
9+
if (isset($arr[$s])) {
10+
assertType('numeric-string', $s);
11+
} else {
12+
assertType('string', $s);
13+
}
14+
assertType('string', $s);
15+
}

src/Type/MixedType.php

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -478,8 +478,10 @@ function () use ($level): string {
478478

479479
public function toBoolean(): BooleanType
480480
{
481-
if ($this->subtractedType !== null && StaticTypeFactory::falsey()->equals($this->subtractedType)) {
482-
return new ConstantBooleanType(true);
481+
if ($this->subtractedType !== null) {
482+
if ($this->subtractedType->isSuperTypeOf(StaticTypeFactory::falsey())->yes()) {
483+
return new ConstantBooleanType(true);
484+
}
483485
}
484486

485487
return new BooleanType();

tests/PHPStan/Analyser/nsrt/mixed-subtract.php

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -53,4 +53,9 @@ function subtract(mixed $m, $moreThenFalsy) {
5353
assertType('mixed', $m);
5454
assertType('bool', (bool) $m); // could be true
5555
}
56+
57+
if ($m != 0 && !is_array($m) && $m != null && !is_object($m)) { // subtract more types then falsy
58+
assertType("mixed~(0|0.0|''|'0'|array|object|false|null)", $m);
59+
assertType('true', (bool) $m);
60+
}
5661
}

0 commit comments

Comments
 (0)