Skip to content

Error when checking for optional array keys (from parse_url) #3009

@szymach

Description

@szymach

Bug report

So, I know this is quite similar to #2001, but is maybe worth considering. I have a piece of code that builds a new request based on parameters from the current url:

        $redirectUrlParts = parse_url($redirectUri);
        if (false === is_array($redirectUrlParts) || true === array_key_exists('host', $redirectUrlParts)) {
            return null;
        }

        $redirectServer = [
            'SCRIPT_FILENAME' => $this->request->server->get('SCRIPT_FILENAME'),
            'PHP_SELF' => $this->request->server->get('PHP_SELF'),
            'REQUEST_URI' => $redirectUrlParts['path'] ?? '',
        ];

        if (true === array_key_exists('query', $redirectUrlParts)) {
            $redirectServer['QUERY_STRING'] = $redirectUrlParts['query'];
        }

        return new Request([], [], [], [], [], $redirectServer);

Notice the first condition checking for the host key. The idea is that if a host is provided, there should not be anything done since the request is to an external domain. The problem is that phpstan breaks on the if (true === array_key_exists('query', $redirectUrlParts)) comparison, resulting in:

Call to function array_key_exists() with 'query' and array() will always evaluate to false.  
Strict comparison using === between true and false will always evaluate to false.  

The problem I think stems from the host comparison - if function is terminated when it exists, phpstan assumes that if it does not, then there is a non-defined array that it is dealing with. My current workaround is to move that condition after checking for the query key.

EDIT here is the playground bit https://phpstan.org/r/d44f7d25-ab97-4ec7-9190-18b20060ee43 - I do not know how to provide Symfony class to remove the non existent class errors.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions