Skip to content

Commit

Permalink
Added a From::first method
Browse files Browse the repository at this point in the history
  • Loading branch information
prewk committed Feb 6, 2018
1 parent f6ac3ae commit 885831e
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 0 deletions.
8 changes: 8 additions & 0 deletions spec/Option/FromSpec.php
Expand Up @@ -3,6 +3,7 @@
namespace spec\Prewk\Option;

use PhpSpec\ObjectBehavior;
use Prewk\Option\OptionException;

class FromSpec extends ObjectBehavior
{
Expand Down Expand Up @@ -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]);
}
}
19 changes: 19 additions & 0 deletions src/Option/From.php
Expand Up @@ -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<V> from the first item, returning None if T is empty
*
* @param $iterable Iterable T<V>
* @return Option Option<V>
*/
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;
}
}

0 comments on commit 885831e

Please sign in to comment.