File tree Expand file tree Collapse file tree 2 files changed +54
-0
lines changed Expand file tree Collapse file tree 2 files changed +54
-0
lines changed Original file line number Diff line number Diff line change @@ -42,3 +42,23 @@ public function ifSome(callable $f): Maybe
42
42
}
43
43
};
44
44
}
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
+ }
Original file line number Diff line number Diff line change 4
4
5
5
use Careship \Functional \Maybe \None ;
6
6
use Careship \Functional \Maybe \Some ;
7
+ use PHPUnit \Framework \MockObject \Rule \InvokedCount as InvokedCountMatcher ;
7
8
use PHPUnit \Framework \TestCase ;
9
+ use function Careship \Functional \Maybe \handle_maybe ;
8
10
use function Careship \Functional \Maybe \none ;
9
11
use function Careship \Functional \Maybe \some ;
10
12
@@ -59,4 +61,36 @@ public function none_if_some_is_a_no_op()
59
61
$ spy ->myMethod ();
60
62
});
61
63
}
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
+ }
62
96
}
You can’t perform that action at this time.
0 commit comments