skip to Main Content

I have the following code and want to get it through Psalm static checks:

if (
    empty($sessions[$token]->product)
    || !is_object($sessions[$token]->product)
) {
     continue;
}

if (
    empty($sessions[$token]->product->view_list)
    || !is_array($sessions[$token]->product->view_list)
) {
    continue;
}

foreach ($sessions[$token]->product->view_list as $view) {
    if (!($view instanceof stdClass) || empty($view->color_list) || !is_array($view->color_list)) {
        continue;
    }
    ...

I am getting

ERROR: MixedAssignment
at ...
Unable to determine the type that $view is being assigned to (see https://psalm.dev/032)
                foreach ($sessions[$token]->product->view_list as $view) {

As you can see I tried in the foreach to already ensure the type of $view (it comes from an external API), but Psalm is not convinced.

I also tried a type annotation /** @var stdClass $view */ but this does not seem right and also not work.

EDIT: if I use a typehint, phpstan complains to use an assert. I also don’t want to use an assert, because it would break the flow, I want to continue instead.

2

Answers


  1. Chosen as BEST ANSWER

    So this seems to make psalm (and myself, coworkers, customer) happy:

    $list = $sessions[$token]->product->view_list ?? [];
    
    if (!is_array($list)) {
        continue;
    }
    
    /** @var mixed $view */
    foreach ($list as $view) {
        if (!($view instanceof stdClass) || empty($view->color_list) || !is_array($view->color_list)) {
            continue;
        }
    

    But PHPStorm complains about the @var mixed $view ... hmm .. okay


  2. Try this:

    if (
        empty($sessions[$token]->product->view_list)
        || !is_array($sessions[$token]->product->view_list)
    ) {
        continue;
    }
    
    //* @var array $list */
    $list = $sessions[$token]->product->view_list;
    
    foreach ($list as $view) {
        if (!($view instanceof stdClass) || empty($view->color_list) || !is_array($view->color_list)) {
            continue;
        }
        ...
    

    Read more: https://psalm.dev/articles/easier-to-diagnose-mixed-issues

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search