From 885831e032b2791660ef0ad94e9588ca6b72f3e6 Mon Sep 17 00:00:00 2001 From: Oskar Thornblad Date: Tue, 6 Feb 2018 10:38:06 +0100 Subject: [PATCH] Added a From::first method --- spec/Option/FromSpec.php | 8 ++++++++ src/Option/From.php | 19 +++++++++++++++++++ 2 files changed, 27 insertions(+) diff --git a/spec/Option/FromSpec.php b/spec/Option/FromSpec.php index d5f0e24..0e0162b 100644 --- a/spec/Option/FromSpec.php +++ b/spec/Option/FromSpec.php @@ -3,6 +3,7 @@ namespace spec\Prewk\Option; use PhpSpec\ObjectBehavior; +use Prewk\Option\OptionException; class FromSpec extends ObjectBehavior { @@ -44,4 +45,11 @@ function it_creates_a_none_from_an_empty_value() $this::emptyable("0")->isNone()->shouldBe(true); $this::emptyable([])->isNone()->shouldBe(true); } + + function it_creates_a_some_from_an_iterable_value() + { + $this::first([])->isNone()->shouldBe(true); + $this::first(["foo"])->isSome()->shouldBe(true); + $this->shouldThrow(OptionException::class)->during("first", [null]); + } } diff --git a/src/Option/From.php b/src/Option/From.php index 5a30e31..608e9cc 100644 --- a/src/Option/From.php +++ b/src/Option/From.php @@ -51,4 +51,23 @@ public static function emptyable($thing): Option { return !empty($thing) ? new Some($thing) : new None; } + + /** + * Iterates over T and creates a Some from the first item, returning None if T is empty + * + * @param $iterable Iterable T + * @return Option Option + */ + public static function first($iterable): Option + { + if (!is_iterable($iterable)) { + throw new OptionException("Couldn't create Option from first item in non-iterable"); + } + + foreach ($iterable as $item) { + return new Some($item); + } + + return new None; + } } \ No newline at end of file