Skip to content

Commit 9865f66

Browse files
author
Nicolò Pignatelli
authored
Added handle_maybe function (#2)
1 parent 10c844a commit 9865f66

File tree

2 files changed

+54
-0
lines changed

2 files changed

+54
-0
lines changed

src/Maybe/functions.php

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -42,3 +42,23 @@ public function ifSome(callable $f): Maybe
4242
}
4343
};
4444
}
45+
46+
/**
47+
* @template T
48+
* @template U
49+
* @template W
50+
* @psalm-param Maybe<T> $maybe
51+
* @psalm-param callable(T):U $someHandler
52+
* @psalm-param callable():W $noneHandler
53+
* @psalm-return U|W
54+
*/
55+
function handle_maybe(Maybe $maybe, callable $someHandler, callable $noneHandler) {
56+
switch (true) {
57+
case $maybe instanceof Some:
58+
return $someHandler($maybe->extract());
59+
case $maybe instanceof None:
60+
return $noneHandler();
61+
default:
62+
throw new \LogicException(sprintf('Unknown maybe type %s', get_class($maybe)));
63+
}
64+
}

tests/Maybe/FunctionsTest.php

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,9 @@
44

55
use Careship\Functional\Maybe\None;
66
use Careship\Functional\Maybe\Some;
7+
use PHPUnit\Framework\MockObject\Rule\InvokedCount as InvokedCountMatcher;
78
use PHPUnit\Framework\TestCase;
9+
use function Careship\Functional\Maybe\handle_maybe;
810
use function Careship\Functional\Maybe\none;
911
use function Careship\Functional\Maybe\some;
1012

@@ -59,4 +61,36 @@ public function none_if_some_is_a_no_op()
5961
$spy->myMethod();
6062
});
6163
}
64+
65+
/** @test */
66+
public function some_handler_is_invoked_in_handle_maybe()
67+
{
68+
$someSpy = $this->getMockBuilder(\stdClass::class)->addMethods(['spy'])->getMock();
69+
$someSpy->expects($this->exactly(1))->method('spy');
70+
71+
$noneSpy = $this->getMockBuilder(\stdClass::class)->addMethods(['spy'])->getMock();
72+
$noneSpy->expects($this->never())->method('spy');
73+
74+
handle_maybe(
75+
some('foo'),
76+
[$someSpy, 'spy'],
77+
[$noneSpy, 'spy']
78+
);
79+
}
80+
81+
/** @test */
82+
public function none_handler_is_invoked_in_handle_maybe()
83+
{
84+
$someSpy = $this->getMockBuilder(\stdClass::class)->addMethods(['spy'])->getMock();
85+
$someSpy->expects($this->never())->method('spy');
86+
87+
$noneSpy = $this->getMockBuilder(\stdClass::class)->addMethods(['spy'])->getMock();
88+
$noneSpy->expects($this->exactly(1))->method('spy');
89+
90+
handle_maybe(
91+
none(),
92+
[$someSpy, 'spy'],
93+
[$noneSpy, 'spy']
94+
);
95+
}
6296
}

0 commit comments

Comments
 (0)