How to make PHPStan understand a function asserts the existence of an array key

114 views Asked by At

PHPStan can recognise we check if array key exists:

<?php declare(strict_types = 1);

/** @return array<mixed> */
function returnMixedArray(): array {
    return [];
}

/**
 * @return array{
 *     existing_key: mixed
 * }
 */
function narrowMixedArrayKeys(): array {
    $foo = returnMixedArray();

    assert(array_key_exists('existing_key', $foo));
    
    return $foo;
}

(This example in playground.)

I want to check multiple keys' existence, and make PHPStan realise what I'm doing.

I tried writing a generic function, but PHPStan doesn't understand what I'm trying to tell it:

<?php declare(strict_types = 1);

/**
 * @param string $keys
 * @param array<int|string> $array
 */
function assertKeys(array $array, string ...$keys): void {
    foreach ($keys as $key) {
        assert(array_key_exists($key, $array));
    }
}

Is there a way to make PHPStan understand a function asserts the existence of a key?

I realise I should be using objects instead of arrays, I'm forced to work with legacy code I want to secure for now.

0

There are 0 answers