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

Possible to improve/preserve non-empty-string type when \substr(T, 0, positive-int) is used? #11086

Open
Ocramius opened this issue Aug 28, 2024 · 1 comment

Comments

@Ocramius
Copy link
Contributor

Given following snippet ( https://psalm.dev/r/7528930261 ) :

<?php

/**
 * @param non-empty-string $in
 * @return non-empty-string
 */
function cut_to_4_chars(string $in): string {
    return \substr($in, 0, 4);
}

Psalm correctly detects that substr() may lead to an empty string:

Psalm output (using commit [16b24bd](https://github.com/vimeo/psalm/commit/16b24bd)): 

INFO: [LessSpecificReturnStatement](https://psalm.dev/129) - 8:12 - The type 'string' is more general than the declared return type 'non-empty-string' for cut_to_4_chars

INFO: [MoreSpecificReturnType](https://psalm.dev/070) - 5:12 - The declared return type 'non-empty-string' for cut_to_4_chars is more specific than the inferred return type 'string'

I'm wondering if it's worth expanding the substr() signature so that it detects the non-empty-string case for a 0 index, and a positive length.

Copy link

I found these snippets:

https://psalm.dev/r/7528930261
<?php

/**
 * @param non-empty-string $in
 * @return non-empty-string
 */
function cut_to_4_chars(string $in): string {
    return \substr($in, 0, 4);
}
Psalm output (using commit 16b24bd):

INFO: LessSpecificReturnStatement - 8:12 - The type 'string' is more general than the declared return type 'non-empty-string' for cut_to_4_chars

INFO: MoreSpecificReturnType - 5:12 - The declared return type 'non-empty-string' for cut_to_4_chars is more specific than the inferred return type 'string'

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant