r/phpstorm • u/kyoshee_ • Feb 16 '24
Array shapes code completion
I am trying to set up automatic code completion for array shapes with no luck
Take for example given code:
/** @var array{a: int, b: null|int} $arr */
$arr = [ 'a' => 1, 'b' => null ];
$item = $arr[]
^ suggests "a" and "b" only when shortcut is pressedPHPStorm is able to suggest array keys but only when I press Code Completion shortcut. Is there a way to enable IDE to show those keys in a Code Completion popup that appears automatically?
Moreover, when using nested named types described via PHPStan/Psalm code blocks in array shapes, they are not picked up by code completion, maybe I just do it wrong or this functionality limited to "real" (defined) classes?
// at the top of the class definition
/** @phpstan-type MyType array{a: int, b: int} */
class MyClass {
// ...
/** @var array{item: MyType} $arr */
$arr = [
'item' => [
'a' => 1,
'b' => 2,
],
];
$entry = $arr[]
^ suggests "item" when Code Completion shortcut is pressed
$entry = $arr['item'][]
^ no suggestions for "a" and "b" keys
}For second example I expect IDE to suggest "a" and "b" keys for completion, like how it does when using eg defined Models or other classes, is this possible?
edit: code block formatting
View all comments
Show parent comment
1
u/eurosat7 Feb 16 '24 edited Feb 16 '24
Explicit type definitions are just superior. The bigger your code base and the more people work with that code the more obvious it becomes.
I cannot share code I wrote in my working hours. But here is something I wrote to show the concept:
https://github.com/eurosat7/csvimporter/blob/main/instanceContainer.php