File tree Expand file tree Collapse file tree 2 files changed +59
-0
lines changed
src/Illuminate/Collections Expand file tree Collapse file tree 2 files changed +59
-0
lines changed Original file line number Diff line number Diff line change @@ -807,6 +807,34 @@ public static function shuffle($array)
807
807
return (new Randomizer )->shuffleArray ($ array );
808
808
}
809
809
810
+ /**
811
+ * Get the first item in the collection, but only if exactly one item exists. Otherwise, throw an exception.
812
+ *
813
+ * @param array $array
814
+ * @param callable $callback
815
+ *
816
+ * @throws \Illuminate\Support\ItemNotFoundException
817
+ * @throws \Illuminate\Support\MultipleItemsFoundException
818
+ */
819
+ public static function sole ($ array , ?callable $ callback = null )
820
+ {
821
+ if ($ callback ) {
822
+ $ array = static ::where ($ array , $ callback );
823
+ }
824
+
825
+ $ count = count ($ array );
826
+
827
+ if ($ count === 0 ) {
828
+ throw new ItemNotFoundException ;
829
+ }
830
+
831
+ if ($ count > 1 ) {
832
+ throw new MultipleItemsFoundException ($ count );
833
+ }
834
+
835
+ return static ::first ($ array );
836
+ }
837
+
810
838
/**
811
839
* Sort the array using the given callback or "dot" notation.
812
840
*
Original file line number Diff line number Diff line change 6
6
use Illuminate \Support \Arr ;
7
7
use Illuminate \Support \Carbon ;
8
8
use Illuminate \Support \Collection ;
9
+ use Illuminate \Support \ItemNotFoundException ;
10
+ use Illuminate \Support \MultipleItemsFoundException ;
9
11
use InvalidArgumentException ;
10
12
use PHPUnit \Framework \TestCase ;
11
13
use stdClass ;
@@ -1067,6 +1069,35 @@ public function testShuffleKeepsSameValues()
1067
1069
$ this ->assertEquals ($ input , $ shuffled );
1068
1070
}
1069
1071
1072
+ public function testSoleReturnsFirstItemInCollectionIfOnlyOneExists ()
1073
+ {
1074
+ $ this ->assertSame ('foo ' , Arr::sole (['foo ' ]));
1075
+
1076
+ $ array = [
1077
+ ['name ' => 'foo ' ],
1078
+ ['name ' => 'bar ' ],
1079
+ ];
1080
+
1081
+ $ this ->assertSame (
1082
+ ['name ' => 'foo ' ],
1083
+ Arr::sole ($ array , fn (array $ value ) => $ value ['name ' ] === 'foo ' )
1084
+ );
1085
+ }
1086
+
1087
+ public function testSoleThrowsExceptionIfNoItemsExist ()
1088
+ {
1089
+ $ this ->expectException (ItemNotFoundException::class);
1090
+
1091
+ Arr::sole (['foo ' ], fn (string $ value ) => $ value === 'baz ' );
1092
+ }
1093
+
1094
+ public function testSoleThrowsExceptionIfMoreThanOneItemExists ()
1095
+ {
1096
+ $ this ->expectExceptionObject (new MultipleItemsFoundException (2 ));
1097
+
1098
+ Arr::sole (['baz ' , 'foo ' , 'baz ' ], fn (string $ value ) => $ value === 'baz ' );
1099
+ }
1100
+
1070
1101
public function testEmptyShuffle ()
1071
1102
{
1072
1103
$ this ->assertEquals ([], Arr::shuffle ([]));
You can’t perform that action at this time.
0 commit comments