Skip to content

Commit d916b3f

Browse files
committed
Implement TypeSpecifierContext->getReturnType()
1 parent 2fe4e0f commit d916b3f

File tree

2 files changed

+36
-15
lines changed

2 files changed

+36
-15
lines changed

src/Analyser/TypeSpecifier.php

+21-15
Original file line numberDiff line numberDiff line change
@@ -331,21 +331,6 @@ public function specifyTypesInCondition(
331331
}
332332
}
333333

334-
if (
335-
!$context->null()
336-
&& $expr->right instanceof FuncCall
337-
&& count($expr->right->getArgs()) >= 3
338-
&& $expr->right->name instanceof Name
339-
&& in_array(strtolower((string) $expr->right->name), ['preg_match'], true)
340-
&& IntegerRangeType::fromInterval(0, null)->isSuperTypeOf($leftType)->yes()
341-
) {
342-
return $this->specifyTypesInCondition(
343-
$scope,
344-
new Expr\BinaryOp\NotIdentical($expr->right, new ConstFetch(new Name('false'))),
345-
$context,
346-
)->setRootExpr($expr);
347-
}
348-
349334
if (
350335
!$context->null()
351336
&& $expr->right instanceof FuncCall
@@ -466,6 +451,27 @@ public function specifyTypesInCondition(
466451
}
467452
}
468453

454+
if (
455+
!$context->null()
456+
&& $expr->left instanceof Node\Scalar
457+
&& $expr->right instanceof Expr\FuncCall
458+
&& $expr->right->name instanceof Name
459+
&& in_array(strtolower((string) $expr->right->name), ['preg_match'], true)
460+
) {
461+
if (!$scope instanceof MutatingScope) {
462+
throw new ShouldNotHappenException();
463+
}
464+
$newScope = $scope->filterBySpecifiedTypes($result);
465+
$callType = $newScope->getType($expr->right);
466+
$newContext = $context->newWithReturnType($callType);
467+
468+
$result = $result->unionWith($this->specifyTypesInCondition(
469+
$scope,
470+
$expr->right,
471+
$newContext,
472+
)->setRootExpr($expr));
473+
}
474+
469475
return $result;
470476

471477
} elseif ($expr instanceof Node\Expr\BinaryOp\Greater) {

src/Analyser/TypeSpecifierContext.php

+15
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33
namespace PHPStan\Analyser;
44

55
use PHPStan\ShouldNotHappenException;
6+
use PHPStan\Type\Type;
67

78
/**
89
* @api
@@ -21,6 +22,8 @@ final class TypeSpecifierContext
2122
/** @var self[] */
2223
private static array $registry;
2324

25+
private ?Type $returnType = null;
26+
2427
private function __construct(private ?int $value)
2528
{
2629
}
@@ -89,4 +92,16 @@ public function null(): bool
8992
return $this->value === null;
9093
}
9194

95+
public function newWithReturnType(Type $type): self
96+
{
97+
$new = self::create($this->value);
98+
$new->returnType = $type;
99+
return $new;
100+
}
101+
102+
public function getReturnType(): ?Type
103+
{
104+
return $this->returnType;
105+
}
106+
92107
}

0 commit comments

Comments
 (0)