Skip to content

False positive on arrays transformation with exceptions #2273

@kiler129

Description

@kiler129

Bug report

First of all: I'm sorry for naming that bug in such a weird way, I had no idea how to describe it ;)

The problem originates from checking the array element and throwing exception if it doesn't match. It seems like PhpStan doesn't see the exception and still thinks the code below will be executed: https://phpstan.org/r/2a565ae0-7c2c-4c5f-964d-e235c775bb5b

Code snippet that reproduces the problem

<?php declare(strict_types = 1);

class foo {
    /**
     * @param string[] $x
     */
    public function __construct(array $x)
    {
        var_dump($x);
    }
}

class bar extends foo {
    /**
     * {@inheritDoc}
     */
    public function __construct(array $x)
    {
        foreach ($x as $k => $v) {
            $x[$k] = \realpath($v);
            if ($x[$k] === false) {
                throw new \Exception();
            }
        }
        
        parent::__construct($x);
    }
}

Expected output

The code should not return erros. As of now it returns 2 errors which I believe are stemming from the same problem:

+-------------------------------------------------------------------------------------------------------------------+
| Line | test.php                                                                                                   |
+-------------------------------------------------------------------------------------------------------------------+
| 20   | Parameter #1 $path of function realpath expects string, string|false given.                                |
| 26   | Parameter #1 $x of method foo::__construct() expects array<string>, array<string|false> given. |
+-------------------------------------------------------------------------------------------------------------------+

Introducing a new intermediate variable seems to fix the problem: https://phpstan.org/r/f04e6f41-9490-498a-8ed5-ce98e9529e0b

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions