/** * @param callable $hof * @return Success|Failure */ function Attempt(callable $hof) { try { return Success(call_user_func($hof)); } catch (\Exception $e) { return Failure($e); } }
public function testFlatMap() { $c = Rescue($this->theNumber7()); $c = $c->flatMap(function ($v) { return Failure(new RuntimeException()); }); $this->assertThat($c->getOrElse(1), $this->equalTo(1)); }
/** * @param callable $hof (): Attempt * @return Attempt * @throws \Exception on function not returning a Attempt subtype */ public function orElse(callable $hof) { if ($this->isSuccess()) { return $this; } try { $result = $hof(); } catch (\Exception $e) { return Failure($e); } return static::assertRootType($result); }
/** * @inheritdoc */ public function transform(callable $success, callable $failure) { try { $result = call_user_func($success, $this->value, $this); } catch (\Exception $e) { return Failure($e); } return static::assertRootType($result); }