[TypeDeclaration] Add param type to array map closure
Changes
- Adds a new rule for type hinting closures used with
array_map. - Adds tests.
Why
Another rule from me which will deal with the difficulties of type hinting closures. It takes the key and value types of all the arrays provided and then type hints them. If more than one array is provide and the value/key types are different it will work out the union type.
-array_map(function ($value, $key): string {
+array_map(function (string $value, int $key): string {
return $value . $key;
}, $strings);
Since this rule works on phpdoc types and most other rules only work on native types, do we need some special documentation or rule-set for it?
Since this rule works on phpdoc types and most other rules only work on native types, do we need some special documentation or rule-set for it?
@staabm
I've just recently merged a rule that also interacts with the phpdoc information https://github.com/rectorphp/rector-src/pull/6345
There are also rules that generate PHPDoc tags https://getrector.com/rule-detail/add-return-type-declaration-from-yields-rector
I think we should be safe here, despite risk of docblocks. Typed closures could have a standalone set, as quite nich area.
How many other closure rules that help with native array_ () cases we have here?
There's a number of functions off the top of my head that are in core PHP.
- array_walk
- array_filter
- array_reduce
- array_diff_uassoc
my point is, that inferring types based on phpdocs has a big risk of beeing wrong. I don't say that I don't like these new rules, but these make only sense if you apply them in a codebase which already has decent correct native type coverage.
thats why I think these phpdoc based rules should be somehow identifiable by the rector-user
I can see what you mean but technically all rules can be informed by incorrect hinting. PHPStan is informed by both native types and phpdocs. Checking an ObjectType might be only established by a PHPDoc for a parameter etc.
My appologies for delays, we got lot of upgrade work recently.
I'll make sure this is merged :+1:
@peterfox rebase is needed, ensure it works with the way phpstan 2 and phpdoc-parser 2 detect it on latest main.
@samsonasik I have now rebased the rules. No changes required.
Thank you Peter! Let's ship it 👌