1+ <?php
2+
3+ namespace MonadPHP ;
4+
5+ class Promise extends Monad {
6+
7+ protected $ isResolved = false ;
8+ protected $ succeed = null ;
9+
10+ protected $ children = array ();
11+ protected $ success ;
12+ protected $ failure ;
13+
14+ public function __construct ($ success = null , $ failure = null ) {
15+ $ this ->success = $ success ;
16+ $ this ->failure = $ failure ;
17+ }
18+
19+ public function unit ($ success = null , $ failure = null ) {
20+ return new static ($ success , $ failure );
21+ }
22+
23+ public function bind ($ success , $ failure ) {
24+ $ obj = $ this ->unit ($ success , $ failure );
25+ if ($ this ->isResolved ) {
26+ if ($ this ->succeed ) {
27+ $ obj ->succeed ($ this ->value );
28+ } else {
29+ $ obj ->fail ($ this ->value );
30+ }
31+ } else {
32+ $ this ->children [] = $ obj ;
33+ }
34+ return $ obj ;
35+ }
36+
37+ public function succeed ($ value ) {
38+ $ this ->resolve (true , $ value );
39+ }
40+
41+ public function fail ($ value ) {
42+ $ this ->resolve (false , $ value );
43+ }
44+
45+ protected function resolve ($ status , $ value ) {
46+ if ($ this ->isResolved ) {
47+ throw new \BadMethodCallException ('Promise already resolved ' );
48+ }
49+ $ this ->value = $ value ;
50+ $ this ->isResolved = true ;
51+ $ this ->succeed = $ status ;
52+ $ callback = $ status ? $ this ->success : $ this ->failure ;
53+ if ($ callback ) {
54+ call_user_func ($ callback , $ value );
55+ }
56+ $ method = $ status ? 'succeed ' : 'fail ' ;
57+ foreach ($ this ->children as $ child ) {
58+ $ child ->$ method ($ value );
59+ }
60+ }
61+
62+ public function when ($ success = null , $ failure = null ) {
63+ return $ this ->bind ($ success , $ failure );
64+ }
65+ }
0 commit comments