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

[11.x] Add generics for Arr::first() #50514

Merged
merged 2 commits into from
Mar 13, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 8 additions & 4 deletions src/Illuminate/Collections/Arr.php
Original file line number Diff line number Diff line change
Expand Up @@ -181,10 +181,14 @@ public static function exists($array, $key)
/**
* Return the first element in an array passing a given truth test.
*
* @param iterable $array
* @param callable|null $callback
* @param mixed $default
* @return mixed
* @template TKey
* @template TValue
* @template TFirstDefault
nunomaduro marked this conversation as resolved.
Show resolved Hide resolved
*
* @param iterable<TKey, TValue> $array
* @param (callable(TValue, TKey): bool)|null $callback
* @param TFirstDefault|(\Closure(): TFirstDefault) $default
* @return TValue|TFirstDefault
*/
public static function first($array, callable $callback = null, $default = null)
{
Expand Down
56 changes: 56 additions & 0 deletions types/Support/Arr.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
<?php

use Illuminate\Support\Arr;

use function PHPStan\Testing\assertType;

$array = [new User];
/** @var iterable<int, User> $iterable */
$iterable = [];
/** @var Traversable<int, User> $traversable */
$traversable = [];

assertType('User|null', Arr::first($array));
assertType('User|null', Arr::first($array, function ($user) {
assertType('User', $user);

return true;
}));
assertType('string|User', Arr::first($array, function ($user) {
assertType('User', $user);

return false;
}, 'string'));
assertType('string|User', Arr::first($array, null, function () {
return 'string';
}));

assertType('User|null', Arr::first($iterable));
assertType('User|null', Arr::first($iterable, function ($user) {
assertType('User', $user);

return true;
}));
assertType('string|User', Arr::first($iterable, function ($user) {
assertType('User', $user);

return false;
}, 'string'));
assertType('string|User', Arr::first($iterable, null, function () {
return 'string';
}));

assertType('User|null', Arr::first($traversable));
assertType('User|null', Arr::first($traversable, function ($user) {
assertType('User', $user);

return true;
}));
assertType('string|User', Arr::first($traversable, function ($user) {
assertType('User', $user);

return false;
}, 'string'));
assertType('string|User', Arr::first($traversable, null, function () {
return 'string';
}));
Loading