Skip to content

Commit

Permalink
Add Collection@isSingle method
Browse files Browse the repository at this point in the history
  • Loading branch information
JosephSilber committed Mar 2, 2021
1 parent 94c2385 commit b72178d
Show file tree
Hide file tree
Showing 4 changed files with 37 additions and 0 deletions.
10 changes: 10 additions & 0 deletions src/Illuminate/Collections/Collection.php
Original file line number Diff line number Diff line change
Expand Up @@ -553,6 +553,16 @@ public function isEmpty()
return empty($this->items);
}

/**
* Determine if the collection contains a single element.
*
* @return bool
*/
public function isSingle()
{
return $this->count() === 1;
}

/**
* Join all items from the collection using a string. The final items can use a separate glue string.
*
Expand Down
10 changes: 10 additions & 0 deletions src/Illuminate/Collections/LazyCollection.php
Original file line number Diff line number Diff line change
Expand Up @@ -556,6 +556,16 @@ public function isEmpty()
return ! $this->getIterator()->valid();
}

/**
* Determine if the collection contains a single element.
*
* @return bool
*/
public function isSingle()
{
return $this->take(2)->count() === 1;
}

/**
* Join all items from the collection using a string. The final items can use a separate glue string.
*
Expand Down
10 changes: 10 additions & 0 deletions tests/Support/SupportCollectionTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -541,6 +541,16 @@ public function testCountableByWithCallback($collection)
})->all());
}

/**
* @dataProvider collectionClassProvider
*/
public function testIsSingle($collection)
{
$this->assertFalse((new $collection([]))->isSingle());
$this->assertTrue((new $collection([1]))->isSingle());
$this->assertFalse((new $collection([1, 2]))->isSingle());
}

public function testIterable()
{
$c = new Collection(['foo']);
Expand Down
7 changes: 7 additions & 0 deletions tests/Support/SupportLazyCollectionIsLazyTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -484,6 +484,13 @@ public function testIsNotEmptyIsLazy()
});
}

public function testIsSingleIsLazy()
{
$this->assertEnumerates(2, function ($collection) {
$collection->isSingle();
});
}

public function testJoinIsLazy()
{
$this->assertEnumeratesOnce(function ($collection) {
Expand Down

0 comments on commit b72178d

Please sign in to comment.