Skip to content

[12.x] Add Arr::soleValue method #55570

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

Closed
wants to merge 3 commits into from
Closed
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
19 changes: 19 additions & 0 deletions src/Illuminate/Collections/Arr.php
Original file line number Diff line number Diff line change
Expand Up @@ -841,6 +841,25 @@ public static function sole($array, ?callable $callback = null)
return static::first($array);
}

/**
* Get a single value from the first element matching the given callback or from the only element in the array.
*
* @template TKey
* @template TValue
*
* @param iterable<TKey, TValue> $array
* @param string|int|callable $key
* @param callable|null $callback
* @return mixed
*
* @throws \Illuminate\Support\ItemNotFoundException
* @throws \Illuminate\Support\MultipleItemsFoundException
*/
public static function soleValue($array, $key, ?callable $callback = null)
{
return static::get(static::sole($array, $callback), $key);
}

/**
* Sort the array using the given callback or "dot" notation.
*
Expand Down
35 changes: 35 additions & 0 deletions tests/Support/SupportArrTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -1098,6 +1098,41 @@ public function testSoleThrowsExceptionIfMoreThanOneItemExists()
Arr::sole(['baz', 'foo', 'baz'], fn (string $value) => $value === 'baz');
}

public function testSoleValueReturnsValueFromSingleElement()
{
$array = [
['name' => 'foo', 'age' => 25],
];

$this->assertSame('foo', Arr::soleValue($array, 'name'));
$this->assertSame(25, Arr::soleValue($array, 'age'));
}

public function testSoleValueReturnsValueFromCallbackFilteredElement()
{
$array = [
['name' => 'foo', 'age' => 25],
['name' => 'bar', 'age' => 30],
];

$this->assertSame('foo', Arr::soleValue($array, 'name', fn (array $value) => $value['age'] === 25));
$this->assertSame(30, Arr::soleValue($array, 'age', fn (array $value) => $value['name'] === 'bar'));
}

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

Arr::soleValue([], 'id');
}

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

Arr::soleValue([['id' => 1], ['id' => 2]], 'id');
}

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