Skip to content
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

[TypeDeclaration] Closure Param Types from Iterator Source #6345

Merged
merged 10 commits into from
Oct 7, 2024

Conversation

peterfox
Copy link
Contributor

@peterfox peterfox commented Oct 2, 2024

Changes

  • Adds a new rule AddClosureParamTypeFromIterableMethodCallRector
  • Adds new methods to TypeUnwrapper
    • unwrapFirstCallableTypeFromUnionType(Type $type): ?Type
    • isIterableTypeValue(string $className, Type $type): bool
    • isIterableTypeKey(string $className, Type $type): bool
  • Adds tests for the rule

Why

This rule should make it easy to type hint closures based on PHPStan's generics.

class Fixture
{
    /**
     * @param Collection<int, string> $collection
     */
    public function run(Collection $collection)
    {
-        return $collection->map(function ($item, $key) {
+        return $collection->map(function (string $item, int $key) {
            return $item . $key;
        });
    }
}

Notes

I'd like to bring this to functions as well, but that will take a bit more effort to establish the iterator source. I'd be open to recommendations of how to put some code from this rule into more reusable classes.

@peterfox peterfox changed the title Closure Param Types from Iterator Source [TypeDeclaration] Closure Param Types from Iterator Source Oct 4, 2024
@peterfox
Copy link
Contributor Author

peterfox commented Oct 6, 2024

Thank you for the review @samsonasik

@TomasVotruba
Copy link
Member

Thank you @peterfox 🙏

@TomasVotruba TomasVotruba merged commit 4c84d6c into rectorphp:main Oct 7, 2024
36 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

4 participants