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

Cannot deduce correct type #11178

Open
loevgaard opened this issue Dec 4, 2024 · 1 comment
Open

Cannot deduce correct type #11178

loevgaard opened this issue Dec 4, 2024 · 1 comment

Comments

@loevgaard
Copy link

Example
https://psalm.dev/r/8a642de112

Explanation
Since I am checking for all relevant types before line 16, $value can only be string at this point. Psalm doesn't seem to agree.

Am I missing something?

Copy link

I found these snippets:

https://psalm.dev/r/8a642de112
<?php

/**
 * @return ($value is null ? null : \DateTimeImmutable)
 */
function convertDateTime(null|\DateTimeInterface|string $value): ?\DateTimeImmutable
{
    if (null === $value || $value instanceof \DateTimeImmutable) {
        return $value;
    }

    if ($value instanceof \DateTimeInterface) {
        return \DateTimeImmutable::createFromInterface($value);
    }

    $res = \DateTimeImmutable::createFromFormat(\DATE_ATOM, $value);
    if (false === $res) {
        throw new \InvalidArgumentException(sprintf('The value %s is not a valid date time string based on the format %s', $value, \DATE_ATOM));
    }

    return $res;
}
Psalm output (using commit 79ab7e2):

ERROR: PossiblyInvalidCast - 16:61 - DateTimeInterface cannot be cast to string

ERROR: PossiblyInvalidArgument - 16:61 - Argument 2 of DateTimeImmutable::createFromFormat expects string, but possibly different type TGeneratedFromParam0:fn-convertdatetime as DateTimeInterface|string provided

ERROR: PossiblyInvalidArgument - 18:124 - Argument 2 of sprintf expects float|int|object{__tostring()}|string, but possibly different type TGeneratedFromParam0:fn-convertdatetime as DateTimeInterface|string provided

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