phpstan / phpstan-symfony

Symfony extension for PHPStan
MIT License
707 stars 89 forks source link

Type inference for HeaderBag could support has() #399

Closed Seldaek closed 2 weeks ago

Seldaek commented 3 months ago

Right now calling this triggers an error as the returned header is string|null, but really after ->has($key) returns true, we can assert that ->get($sameKey) will be string. At least as long as there is no other impure call made in between like ->remove() or ->replace()

if ($request->headers->has('foo')) {
    $v = strtolower($request->headers->get('foo'));
}
VincentLanglet commented 2 weeks ago

Hi @Seldaek,

This is untrue.

The has method is based on array_key_exists, which means you can still have a NULL headers.

public function has(string $key): bool
    {
        return \array_key_exists(strtr($key, self::UPPER, self::LOWER), $this->all());
    }

The same issue exists for InputBag/ParameterBag ; I opened https://github.com/phpstan/phpstan-symfony/pull/409

Seldaek commented 2 weeks ago

Yeah I guess you're right from an implementation standpoint. I don't know what would ever cause a header to receive a null value in the real world though, but definitely could happen in tests etc..