Skip to content

Commit 1348ac1

Browse files
committed
TASK: Make type inference in TernaryBranchScope more explicit
1 parent 3487bd9 commit 1348ac1

2 files changed

Lines changed: 17 additions & 9 deletions

File tree

src/TypeSystem/Scope/ShallowScope/TernaryBranchScope.php

Lines changed: 17 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -61,22 +61,31 @@ public function lookupTypeFor(string $name): ?TypeInterface
6161
}
6262

6363
if ($this->conditionNode->root instanceof IdentifierNode && $this->conditionNode->root->value === $name) {
64+
// case `nullableString ? "nullableString is not null" : "nullableString is null"`
6465
return $this->isBranchTrue ? $type->withoutNull() : NullType::get();
6566
}
6667

6768
if (($binaryOperationNode = $this->conditionNode->root) instanceof BinaryOperationNode) {
68-
foreach ($binaryOperationNode->operands as $operand) {
69-
if (!$operand->root instanceof NullLiteralNode
70-
&& !($operand->root instanceof IdentifierNode && $operand->root->value === $name)
71-
) {
72-
return $type;
73-
}
69+
// cases
70+
// `nullableString === null ? "nullableString is null" : "nullableString is not null"`
71+
// `nullableString !== null ? "nullableString is not null" : "nullableString is null"`
72+
if (count($binaryOperationNode->operands->rest) !== 1) {
73+
return $type;
74+
}
75+
$first = $binaryOperationNode->operands->first;
76+
$second = $binaryOperationNode->operands->rest[0];
77+
// case `nullableString === null`
78+
$isFirstToBeLookedUpName = $first->root instanceof IdentifierNode && $first->root->value === $name;
79+
$isFirstComparedToNull = $isFirstToBeLookedUpName && $second->root instanceof NullLiteralNode;
80+
// yodas case `null === nullableString`
81+
$isSecondToBeLookedUpName = $second->root instanceof IdentifierNode && $second->root->value === $name;
82+
$isSecondComparedToNull = $first->root instanceof NullLiteralNode && $isSecondToBeLookedUpName;
83+
if (!$isFirstComparedToNull && !$isSecondComparedToNull) {
84+
return $type;
7485
}
75-
7686
if ($binaryOperationNode->operator === BinaryOperator::EQUAL) {
7787
return $this->isBranchTrue ? NullType::get() : $type->withoutNull();
7888
}
79-
8089
if ($binaryOperationNode->operator === BinaryOperator::NOT_EQUAL) {
8190
return $this->isBranchTrue ? $type->withoutNull() : NullType::get();
8291
}

test/Unit/TypeSystem/Resolver/TernaryOperation/TernaryOperationTypeResolverTest.php

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -54,7 +54,6 @@ public function ternaryOperationExamples(): array
5454
'nullableString === null ? "" : nullableString' => [
5555
'nullableString === null ? "" : nullableString', StringType::get()
5656
],
57-
// Tue es oder tue es nicht. Es gibt kein Versuchen.
5857
'null === nullableString ? "" : nullableString' => [
5958
'null === nullableString ? "" : nullableString', StringType::get()
6059
],

0 commit comments

Comments
 (0)