From ebc0129553ef5d3d5ac505511861be01982b7e11 Mon Sep 17 00:00:00 2001 From: Johannes Meyer Date: Thu, 31 Aug 2023 16:22:41 +0200 Subject: [PATCH 1/2] functions: Add `iterable_value_first` --- src/functions.php | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) diff --git a/src/functions.php b/src/functions.php index 57f2d9b..e7f9be0 100644 --- a/src/functions.php +++ b/src/functions.php @@ -72,6 +72,22 @@ function iterable_key_first($iterable) return null; } +/** + * Get the first value of an iterable + * + * @param iterable $iterable + * + * @return ?mixed + */ +function iterable_value_first($iterable) +{ + foreach ($iterable as $_ => $value) { + return $value; + } + + return null; +} + /** * Yield sets of items from a sorted traversable grouped by a specific criterion gathered from a callback * From df885e7633f3c2187d0a7835a6b595231951cb6e Mon Sep 17 00:00:00 2001 From: raviks789 <33730024+raviks789@users.noreply.github.com> Date: Fri, 1 Sep 2023 13:24:16 +0200 Subject: [PATCH 2/2] Test `iterator_value_first()` --- tests/FunctionsTest.php | 37 +++++++++++++++++++++++++++++++++++++ 1 file changed, 37 insertions(+) diff --git a/tests/FunctionsTest.php b/tests/FunctionsTest.php index 1263a11..e107e66 100644 --- a/tests/FunctionsTest.php +++ b/tests/FunctionsTest.php @@ -246,4 +246,41 @@ public function testYieldGroupsWithCallbackReturningCriterionValueAndKey() ) ); } + + public function testIterableValueFirstReturnsFirstValueIfIterableImplementsIteratorAndIsNotEmpty() + { + $this->assertSame('a', Stdlib\iterable_value_first(new ArrayIterator(['a', 'b']))); + } + + public function testIterableValueFirstReturnsFirstValueIfIterableIsArrayAndIsNotEmpty() + { + $this->assertSame('a', Stdlib\iterable_value_first(['a', 'b'])); + } + + public function testIterableValueFirstReturnsFirstValueIfIterableIsGeneratorAndIsNotEmpty() + { + $this->assertSame('a', Stdlib\iterable_value_first(call_user_func(function () { + yield 'a'; + yield 'b'; + }))); + } + + public function testIterableValueFirstReturnsNullIfIterableImplementsIteratorAndIsEmpty() + { + $this->assertNull(Stdlib\iterable_value_first(new ArrayIterator([]))); + } + + public function testIterableValueFirstReturnsNullIfIterableIsArrayAndIsEmpty() + { + $this->assertNull(Stdlib\iterable_value_first([])); + } + + public function testIterableValueFirstReturnsNullIfIterableIsGeneratorAndIsEmpty() + { + $this->assertNull(Stdlib\iterable_value_first(call_user_func(function () { + return; + /** @noinspection PhpUnreachableStatementInspection Empty generator */ + yield; + }))); + } }