Skip to content

False positive for return type non-empty-string|null when using trim to filter blank strings #12973

@mickverm

Description

@mickverm

Bug report

When returning a non-empty-string|null from a method that checks for blank strings using trim(), PHPStan 2.1.14 reports a false positive error:

/**
 * @return non-empty-string|null
 */
public static function nullIfBlank(?string $value): ?string
{
    if ($value !== null) {
        return \trim($value) === '' ? null : $value;
    }

    return null;
}

Error reported:

Method StringUtil::nullIfBlank() should return non-empty-string|null but returns string|null.

Code snippet that reproduces the problem

https://phpstan.org/r/050ad446-96a4-4d45-8cbf-dbc243d32b64

Expected output

PHPStan should recognize that when trim($value) === '', the method returns null, and otherwise returns the original $value which, by that condition, must be a non-empty-string.

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions