Skip to content

Commit 1824fd8

Browse files
authored
Merge pull request #33 from worksolutions/one-element-streaming
First element collection streaming via predicate
2 parents 8806f05 + 04d7ff6 commit 1824fd8

File tree

3 files changed

+40
-1
lines changed

3 files changed

+40
-1
lines changed

composer.json

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@
33
"description": "Collections library for php language",
44
"minimum-stability": "dev",
55
"license": "MIT",
6-
"version": "1.0.7",
6+
"version": "1.0.8",
77
"authors": [
88
{
99
"name": "Maxim Sokolovsky",

src/WS/Utils/Collections/Functions/Predicates.php

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -288,4 +288,20 @@ public static function whereLessOrEqual(string $property, $value): Closure
288288
return ObjectFunctions::getPropertyValue($ob, $property) <= $value;
289289
};
290290
}
291+
292+
/**
293+
* Returns <Fn($el: mixed): bool> passed only one time with first element
294+
* @return Closure
295+
*/
296+
public static function first(): Closure
297+
{
298+
$runOut = false;
299+
return static function () use (& $runOut) {
300+
if ($runOut) {
301+
return false;
302+
}
303+
$runOut = true;
304+
return true;
305+
};
306+
}
291307
}

tests/WS/Utils/Collections/PredicatesFunctionsTest.php

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@
55

66
namespace WS\Utils\Collections;
77

8+
use PHPUnit\Framework\MockObject\MockBuilder;
89
use PHPUnit\Framework\TestCase;
910
use WS\Utils\Collections\Functions\Predicates;
1011
use WS\Utils\Collections\UnitConstraints\CollectionIsEqual;
@@ -233,4 +234,26 @@ public function matchingValuesFiltering(): void
233234
;
234235
$this->assertThat($filtered, CollectionIsEqual::to([1, 2]));
235236
}
237+
238+
/**
239+
* @test
240+
*/
241+
public function firstValueStreaming(): void
242+
{
243+
// Arrange
244+
$FIRST_VALUE = 5;
245+
$stream = self::toCollection($FIRST_VALUE, 6, 7)->stream();
246+
247+
$runningCount = 0;
248+
// Act
249+
$stream
250+
->filter(Predicates::first())
251+
->each(static function ($value) use ($FIRST_VALUE, & $runningCount) {
252+
$runningCount++;
253+
self::assertEquals($FIRST_VALUE, $value);
254+
});
255+
256+
// Assert
257+
self::assertEquals(1, $runningCount);
258+
}
236259
}

0 commit comments

Comments
 (0)