phpvalidationassociative-arraystatic-analysisphpstan

Why isn't PHPStan complaining about invalid array keys?


Here's the code:

<?php declare(strict_types=1);

/**
 * @param  array{key?: string}  $options
 */
function hello($options)
{
    var_dump($options);
}

hello([
    'WRONG_KEY' => '...',
]);

I would expect phpstan analyze to fail on this code, complaining about unexpected WRONG_KEY in the passed array.

Why it's not failing? Do I miss some configuration or is it how PHPStan supposed to work?


Solution

  • This is about sealed vs. unsealed array shapes.

    Unsealed array shapes allow extra keys. Right now PHPStan’s array shapes mostly act as unsealed, but sometimes it’s inconsistent.

    There’s an open issue about it: https://github.com/phpstan/phpstan/issues/8438 (one of the most upvoted issues so it will get solved sooner or later)