Skip to content

Commit

Permalink
[11.x] Add generics for Arr::first() (#50514)
Browse files Browse the repository at this point in the history
* Add generics for Arr::first()

* Add TKey
  • Loading branch information
phh authored Mar 13, 2024
1 parent edfc124 commit 08acc92
Show file tree
Hide file tree
Showing 2 changed files with 64 additions and 4 deletions.
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
*
* @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';
}));

0 comments on commit 08acc92

Please sign in to comment.