Skip to content
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

infer non-empty-string on literal-string and strlen() #1260

Merged
merged 6 commits into from Apr 29, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
4 changes: 2 additions & 2 deletions src/Analyser/TypeSpecifier.php
Expand Up @@ -235,7 +235,7 @@ public function specifyTypesInCondition(
$newContext = $newContext->negate();
}
$argType = $scope->getType($exprNode->getArgs()[0]->value);
if ($argType instanceof StringType) {
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

primary motivation was killing instanceof StringType checks

if ($argType->isString()->yes()) {
$funcTypes = $this->create($exprNode, $constantType, $context, false, $scope, $rootExpr);
$valueTypes = $this->create($exprNode->getArgs()[0]->value, new AccessoryNonEmptyStringType(), $newContext, false, $scope, $rootExpr);
return $funcTypes->unionWith($valueTypes);
Expand Down Expand Up @@ -535,7 +535,7 @@ public function specifyTypesInCondition(
|| ($context->falsey() && (new ConstantIntegerType(1 - $offset))->isSuperTypeOf($leftType)->yes())
) {
$argType = $scope->getType($expr->right->getArgs()[0]->value);
if ($argType instanceof StringType) {
if ($argType->isString()->yes()) {
$result = $result->unionWith($this->create($expr->right->getArgs()[0]->value, new AccessoryNonEmptyStringType(), $context, false, $scope, $rootExpr));
}
}
Expand Down
24 changes: 24 additions & 0 deletions tests/PHPStan/Analyser/data/non-empty-string.php
Expand Up @@ -89,6 +89,30 @@ public function doBar5(string $s): void
assertType('\'\'', $s);
}

/**
* @param literal-string $s
*/
public function doBar6($s): void
{
if (1 === strlen($s)) {
assertType('literal-string&non-empty-string', $s);
return;
}
assertType('literal-string', $s);
}

/**
* @param literal-string $s
*/
public function doBar7($s): void
{
if (0 < strlen($s)) {
assertType('literal-string&non-empty-string', $s);
return;
}
assertType("''", $s);
}

public function doFoo3(string $s): void
{
if ($s) {
Expand Down