Skip to content

[12.x] Add Arr::sole() method #55070

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

Merged
merged 4 commits into from
Mar 18, 2025
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
28 changes: 28 additions & 0 deletions src/Illuminate/Collections/Arr.php
Original file line number Diff line number Diff line change
Expand Up @@ -807,6 +807,34 @@ public static function shuffle($array)
return (new Randomizer)->shuffleArray($array);
}

/**
* Get the first item in the collection, but only if exactly one item exists. Otherwise, throw an exception.
*
* @param array $array
* @param callable $callback
*
* @throws \Illuminate\Support\ItemNotFoundException
* @throws \Illuminate\Support\MultipleItemsFoundException
*/
public static function sole($array, ?callable $callback = null)
{
if ($callback) {
$array = static::where($array, $callback);
}

$count = count($array);

if ($count === 0) {
throw new ItemNotFoundException;
}

if ($count > 1) {
throw new MultipleItemsFoundException($count);
}

return static::first($array);
}

/**
* Sort the array using the given callback or "dot" notation.
*
Expand Down
31 changes: 31 additions & 0 deletions tests/Support/SupportArrTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,8 @@
use Illuminate\Support\Arr;
use Illuminate\Support\Carbon;
use Illuminate\Support\Collection;
use Illuminate\Support\ItemNotFoundException;
use Illuminate\Support\MultipleItemsFoundException;
use InvalidArgumentException;
use PHPUnit\Framework\TestCase;
use stdClass;
Expand Down Expand Up @@ -1067,6 +1069,35 @@ public function testShuffleKeepsSameValues()
$this->assertEquals($input, $shuffled);
}

public function testSoleReturnsFirstItemInCollectionIfOnlyOneExists()
{
$this->assertSame('foo', Arr::sole(['foo']));

$array = [
['name' => 'foo'],
['name' => 'bar'],
];

$this->assertSame(
['name' => 'foo'],
Arr::sole($array, fn (array $value) => $value['name'] === 'foo')
);
}

public function testSoleThrowsExceptionIfNoItemsExist()
{
$this->expectException(ItemNotFoundException::class);

Arr::sole(['foo'], fn (string $value) => $value === 'baz');
}

public function testSoleThrowsExceptionIfMoreThanOneItemExists()
{
$this->expectExceptionObject(new MultipleItemsFoundException(2));

Arr::sole(['baz', 'foo', 'baz'], fn (string $value) => $value === 'baz');
}

public function testEmptyShuffle()
{
$this->assertEquals([], Arr::shuffle([]));
Expand Down
Loading