Skip to content

Commit b72178d

Browse files
committed
Add Collection@isSingle method
1 parent 94c2385 commit b72178d

File tree

4 files changed

+37
-0
lines changed

4 files changed

+37
-0
lines changed

src/Illuminate/Collections/Collection.php

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -553,6 +553,16 @@ public function isEmpty()
553553
return empty($this->items);
554554
}
555555

556+
/**
557+
* Determine if the collection contains a single element.
558+
*
559+
* @return bool
560+
*/
561+
public function isSingle()
562+
{
563+
return $this->count() === 1;
564+
}
565+
556566
/**
557567
* Join all items from the collection using a string. The final items can use a separate glue string.
558568
*

src/Illuminate/Collections/LazyCollection.php

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -556,6 +556,16 @@ public function isEmpty()
556556
return ! $this->getIterator()->valid();
557557
}
558558

559+
/**
560+
* Determine if the collection contains a single element.
561+
*
562+
* @return bool
563+
*/
564+
public function isSingle()
565+
{
566+
return $this->take(2)->count() === 1;
567+
}
568+
559569
/**
560570
* Join all items from the collection using a string. The final items can use a separate glue string.
561571
*

tests/Support/SupportCollectionTest.php

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -541,6 +541,16 @@ public function testCountableByWithCallback($collection)
541541
})->all());
542542
}
543543

544+
/**
545+
* @dataProvider collectionClassProvider
546+
*/
547+
public function testIsSingle($collection)
548+
{
549+
$this->assertFalse((new $collection([]))->isSingle());
550+
$this->assertTrue((new $collection([1]))->isSingle());
551+
$this->assertFalse((new $collection([1, 2]))->isSingle());
552+
}
553+
544554
public function testIterable()
545555
{
546556
$c = new Collection(['foo']);

tests/Support/SupportLazyCollectionIsLazyTest.php

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -484,6 +484,13 @@ public function testIsNotEmptyIsLazy()
484484
});
485485
}
486486

487+
public function testIsSingleIsLazy()
488+
{
489+
$this->assertEnumerates(2, function ($collection) {
490+
$collection->isSingle();
491+
});
492+
}
493+
487494
public function testJoinIsLazy()
488495
{
489496
$this->assertEnumeratesOnce(function ($collection) {

0 commit comments

Comments
 (0)