Skip to content

Check array_fill_keys arguments #11111

@pableu

Description

@pableu

Feature request

This code is invalid in PHP 8.3 and PHPStan does not detect the problem:

enum Language: string
{
	case ENG = 'eng';
	case FRE = 'fre';
	case GER = 'ger';
	case ITA = 'ita';
	case SPA = 'spa';
	case DUT = 'dut';
	case DAN = 'dan';
}

$langs = [
	Language::ENG, 
	Language::GER,
	Language::DAN,
];

$array = array_fill_keys($langs, null);

(see https://phpstan.org/r/08852987-50be-4812-9e61-c27c36d9cb36)

Actually running the code leads to this error: Object of class Language could not be converted to string

A new rule to detect this kind of mis-use would be nice.

We could also check other invalid accesses:

  • Reading access: var_dump($array[Language::GER]); --> Cannot access offset of type Language on array
  • Write: $array[Language::ITA] = 'foobar'; --> Cannot access offset of type Language on array
  • Unset: unset($array[Language::GER]); --> Cannot unset offset of type Language on array

Did PHPStan help you today? Did it make you happy in any way?

We love having PHPStan in our CI! It helps us catch bugs or inconsistencies early, and it pushes us to add more types and improve our code ❤️

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions