laravel / framework

The Laravel Framework.
https://laravel.com
MIT License
32.44k stars 11k forks source link

Collection `partion` method not returning correct generic types #53283

Open browner12 opened 5 days ago

browner12 commented 5 days ago

Laravel Version

11.29.0

PHP Version

8.3.12

Database Driver & Version

Sqlite 3.43.2

Description

The partition() method of the Illuminate\Database\Eloquent\Collection, as defined in the Illuminate\Support\Traits\EnumeratesValues class possibly does not have the correct generic return types.

https://github.com/laravel/framework/blob/11.x/src/Illuminate/Collections/Traits/EnumeratesValues.php#L501

The issue goes away when I disable and remove the cache of the LaravelIdea plugin. However, I'm not sure if it's an issue with Laravel's definition of the generics, or with how the plugin is parsing the generics. If it's deemed that Laravel is correct, I'll go open this issue in the plugin repo.

Steps To Reproduce

Given the following user table:

id sex birthday
1 male 2002-01-12
2 female 1991-05-05
3 male 2010-12-25

and the following code:

//get users
$users = User::all();

//partition by sex
[$men, $women] = $users->partition(fn ($user) => $user->sex === 'male');

//group men by age
$menGroupedByAge = $men->groupBy(fn ($item) => $item->birthday->age);

dd($users, $men, $women, $menGroupedByAge);

all 4 dumped variables will be of type Illuminate\Database\Eloquent\Collection. However, the IDE is currently thinking $men, $women, and $menGroupedByAge are all of type App\Models\User.

Both our Collection and User classes also have a groupBy() method available to them, but with different signatures. Because the IDE believes $men is a User, it's also warning that it is unacceptable to pass a closure to groupBy().

github-actions[bot] commented 4 days ago

Thank you for reporting this issue!

As Laravel is an open source project, we rely on the community to help us diagnose and fix issues as it is not possible to research and fix every issue reported to us via GitHub.

If possible, please make a pull request fixing the issue you have described, along with corresponding tests. All pull requests are promptly reviewed by the Laravel team.

Thank you!