Skip to content

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 peterfox force-pushed the feature/param-from-iterator branch from af6f78a to 0c2de7c Compare October 6, 2024 10:10
@peterfox
Copy link
Contributor Author

peterfox commented Oct 6, 2024

Thank you for the review @samsonasik

@TomasVotruba
Copy link
Member

Thank you @peterfox 🙏

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