rector-src icon indicating copy to clipboard operation
rector-src copied to clipboard

[TypeDeclaration] Add param type to array map closure

Open peterfox opened this issue 1 year ago • 6 comments

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);

peterfox avatar Oct 12 '24 03:10 peterfox

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 avatar Oct 12 '24 07:10 staabm

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

peterfox avatar Oct 12 '24 12:10 peterfox

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?

TomasVotruba avatar Oct 12 '24 12:10 TomasVotruba

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

peterfox avatar Oct 12 '24 12:10 peterfox

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

staabm avatar Oct 12 '24 12:10 staabm

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.

peterfox avatar Oct 12 '24 12:10 peterfox

My appologies for delays, we got lot of upgrade work recently.

I'll make sure this is merged :+1:

TomasVotruba avatar Nov 18 '24 08:11 TomasVotruba

@peterfox rebase is needed, ensure it works with the way phpstan 2 and phpdoc-parser 2 detect it on latest main.

samsonasik avatar Nov 23 '24 14:11 samsonasik

@samsonasik I have now rebased the rules. No changes required.

peterfox avatar Nov 24 '24 13:11 peterfox

Thank you Peter! Let's ship it 👌

TomasVotruba avatar Dec 14 '24 20:12 TomasVotruba