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

Allow @phpstan-assert to narrow to a truthy or falsy value #11335

Closed
BHSPitMonkey opened this issue Jul 14, 2024 · 2 comments
Closed

Allow @phpstan-assert to narrow to a truthy or falsy value #11335

BHSPitMonkey opened this issue Jul 14, 2024 · 2 comments

Comments

@BHSPitMonkey
Copy link

BHSPitMonkey commented Jul 14, 2024

Feature request

Hi! I have a project with some commonly-used assertion functions that will throw if the given value converts to true (or false). Taking a cue from the examples on Narrowing Types > Custom type-checking functions and methods, I'd love to be able to do something like this:

/** @phpstan-assert truthy $value */
public function throwIfFalsy(mixed $value): void
{
    if (!$value) {
        throw new InvalidTypeException();
    }
}

This would allow, for example, narrowing a variable from SomeClass|null to SomeClass after this function was called. (Or, conversely, a function set up in the opposite way could narrow SomeClass|null to null.)

Did PHPStan help you today? Did it make you happy in any way?

PHPStan is amazing! 💖

@ondrejmirtes
Copy link
Member

Thank you for your kind words!

You can already do this today: @phpstan-assert !0|0.0|''|'0'|array{}|false|null $value

Copy link

This thread has been automatically locked since there has not been any recent activity after it was closed. Please open a new issue for related bugs.

@github-actions github-actions bot locked as resolved and limited conversation to collaborators Aug 15, 2024
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants