New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Better support for compact #2084
Comments
Do people use |
It's debatable. I think
|
yeah, but it's not particularly sugary because it comes in the form of a function that takes a bunch of strings. |
That's pretty common in PHP: constant('constant');
array_map('function', []);
get_parent_class('class'); |
🙈 |
compact is a decent way of removing duplication and possible typos from your code if you want to build an array of names of variables and their values. To build such an array manually could result in misspelling the variable name in the string, or renaming the variable name at some point without updating the string name. If you use compact, it is at least possible for a static analysis tool to let you know when you are referencing a non-existent variable, and phpmd actually does this. I do wish PHP allowed you to just pass the actual variables to compact though, instead of the variable names, and that it would extract the name from the variable somehow. Then Psalm would already know if you are referencing a non-existent variable. Psalm would have slightly better support for compact if it at least understood the returned array key type was a string instead of array-key, although that would not exactly fix the issues of the OP. |
Actually I was interested in making that change myself (improving key type), but I couldn't find anywhere in Psalm's code where return type of compact was specified. It seemed likely to me this would be hard coded somewhere, but I couldn't find it. I did look through the contributions guide, but I still couldn't figure it out.. There is another similar contribution I would like to attempt as well. |
@still-dreaming-1 It's in the callmap. 'compact' => ['array', 'var_name'=>'string|array', '...var_names='=>'string|array'], The first element is the return type, which can be replaced with |
This is fixed |
Thanks! |
Psalm gives an error when
compact()
is used on an undefined variable. However, it still infers the type asarray<array-key, mixed>
.Example (https://psalm.dev/r/bfab55228d):
Example output:
It should be able to treat that example as:
The text was updated successfully, but these errors were encountered: