Skip to content

Improve TypeCombinator::unionWithSubtractedType #4200

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: 2.1.x
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 12 additions & 0 deletions src/Type/TypeCombinator.php
Original file line number Diff line number Diff line change
Expand Up @@ -540,6 +540,18 @@ private static function unionWithSubtractedType(
return $type;
}

if ($subtractedType instanceof SubtractableType) {
$withoutSubtracted = $subtractedType->getTypeWithoutSubtractedType();
if ($withoutSubtracted->isSuperTypeOf($type)->yes()) {
$subtractedSubtractedType = $subtractedType->getSubtractedType();
if ($subtractedSubtractedType === null) {
return new NeverType();
}

return self::intersect($type, $subtractedSubtractedType);
}
}

if ($type instanceof SubtractableType) {
$subtractedType = $type->getSubtractedType() === null
? $subtractedType
Expand Down
27 changes: 27 additions & 0 deletions tests/PHPStan/Analyser/nsrt/subtracted.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
<?php declare(strict_types = 1);

namespace Substracted;


use function PHPStan\Testing\assertType;

class HelloWorld
{
public function sayHello(mixed $date, bool $foo): void
{
if(is_object($date)){

} else {
assertType('mixed~object', $date);

if ($foo) {
$date = new \stdClass();
}
assertType('mixed~object~stdClass', $date);

if (is_object($date)) {
assertType('stdClass', $date);
}
}
}
}
8 changes: 8 additions & 0 deletions tests/PHPStan/Type/TypeCombinatorTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -4143,6 +4143,14 @@ public static function dataIntersect(): iterable
ObjectWithoutClassType::class,
'object',
],
[
[
new MixedType(subtractedType: new ObjectWithoutClassType(new ObjectType('stdClass'))),
new ObjectWithoutClassType(),
],
ObjectType::class,
'stdClass',
],
];

if (PHP_VERSION_ID < 80100) {
Expand Down
Loading