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
ParadoxicalCondition when assignment happens inside conditionals #4374
Labels
Comments
I found these snippets: https://psalm.dev/r/e23bd1a389<?php
function checkDateIsRFC3339(?string $dateString): ?\DateTimeImmutable
{
if (
null === $dateString ||
((false === $date = \DateTimeImmutable::createFromFormat(DATE_RFC3339, $dateString)) &&
(false === $date = \DateTimeImmutable::createFromFormat(DATE_RFC3339_EXTENDED, $dateString)))
) {
return null;
}
return $date;
}
|
Here's a better working rewrite (IMO): https://psalm.dev/r/3d21ee76cc |
I found these snippets: https://psalm.dev/r/3d21ee76cc<?php
function checkDateIsRFC3339(?string $dateString): ?\DateTimeImmutable
{
if (!$dateString) {
return null;
}
$date = \DateTimeImmutable::createFromFormat(DATE_RFC3339, $dateString)
?: \DateTimeImmutable::createFromFormat(DATE_RFC3339_EXTENDED, $dateString);
return $date ?: null;
}
|
Here's a lighter reproducer for the <?php
function foo(string $str): ?int {
if (!($pos = strpos($str, "a")) && !($pos = strpos($str, "b"))) {
return null;
}
return $pos;
} and for the <?php
function foo(string $str): ?int {
if (!$str || (!($pos = strpos($str, "a")) && !($pos = strpos($str, "b")))) {
return null;
}
return $pos;
} |
Thanks for the improved rewrite @muglug 👍 |
danog
pushed a commit
to danog/psalm
that referenced
this issue
Jan 29, 2021
…ssignments in conditionals
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Psalm detects ParadoxicalCondition (and UnusedVariable) but there is no paradox and the variable is used.
https://psalm.dev/r/e23bd1a389
Looks like this is because of the assignment within the conditions, so psalm sees it as 2 comparisons of the same variable with false, but actually the value of the variable changes between the conditionals due to the assignment.
Normally I would be against assignment in conditionals for readability reasons, but In this case it is actually useful for checking multiple formats and stopping and the first that worked.
We can get around this by changing to
but if possible it seems that supporting the assignments within the conditionals would be potentially beneficial elsewhere.
The text was updated successfully, but these errors were encountered: