Skip to content

Commit

Permalink
Added operator suport for the sole() method.
Browse files Browse the repository at this point in the history
  • Loading branch information
ash-jc-allen committed Apr 19, 2021
1 parent 3c4f386 commit 2d3b63c
Show file tree
Hide file tree
Showing 3 changed files with 31 additions and 17 deletions.
24 changes: 15 additions & 9 deletions src/Illuminate/Collections/Collection.php
Expand Up @@ -1056,25 +1056,31 @@ public function splitIn($numberOfGroups)
* Get the first item in the collection, but only if exactly
* item exists. Otherwise, throw an exception.
*
* @param callable|null $callback
* @param mixed $key
* @param mixed $operator
* @param mixed $value
* @return mixed
*
* @throws \Illuminate\Collections\ItemNotFoundException
* @throws \Illuminate\Collections\MultipleItemsFoundException
*/
public function sole(callable $callback = null)
public function sole($key = null, $operator = null, $value = null)
{
$items = $this->when($callback)->filter($callback);
if (func_num_args() <= 1) {
$items = $this->when($key)->filter($key);

if ($items->isEmpty()) {
throw new ItemNotFoundException;
}
if ($items->isEmpty()) {
throw new ItemNotFoundException;
}

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

if ($items->count() > 1) {
throw new MultipleItemsFoundException;
return $items->first();
}

return $items->first();
return $this->sole($this->operatorForWhere(...func_get_args()));
}

/**
Expand Down
22 changes: 14 additions & 8 deletions src/Illuminate/Collections/LazyCollection.php
Expand Up @@ -1014,20 +1014,26 @@ public function split($numberOfGroups)
* Get the first item in the collection, but only if exactly
* item exists. Otherwise, throw an exception.
*
* @param callable|null $callback
* @param mixed $key
* @param mixed $operator
* @param mixed $value
* @return mixed
*
* @throws \Illuminate\Collections\ItemNotFoundException
* @throws \Illuminate\Collections\MultipleItemsFoundException
*/
public function sole(callable $callback = null)
public function sole($key = null, $operator = null, $value = null)
{
return $this
->when($callback)
->filter($callback)
->take(2)
->collect()
->sole();
if (func_num_args() <= 1) {
return $this
->when($key)
->filter($key)
->take(2)
->collect()
->sole();
}

return $this->sole($this->operatorForWhere(...func_get_args()));
}

/**
Expand Down
2 changes: 2 additions & 0 deletions tests/Support/SupportCollectionTest.php
Expand Up @@ -79,6 +79,8 @@ public function testSoleReturnsFirstItemInCollectionIfOnlyOneExists($collection)
]);

$this->assertSame(['name' => 'foo'], $collection->where('name', 'foo')->sole());
$this->assertSame(['name' => 'foo'], $collection->sole('name', '=', 'foo'));
$this->assertSame(['name' => 'foo'], $collection->sole('name', 'foo'));
}

/**
Expand Down

0 comments on commit 2d3b63c

Please sign in to comment.