Skip to content

Commit 389de6e

Browse files
committed
Add Promise class
1 parent 25e9bfa commit 389de6e

2 files changed

Lines changed: 108 additions & 0 deletions

File tree

src/React/Promise/Promise.php

Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
<?php
2+
3+
namespace React\Promise;
4+
5+
class Promise implements PromiseInterface
6+
{
7+
private $deferred;
8+
9+
public function __construct($resolver, $canceller = null)
10+
{
11+
if (!is_callable($resolver)) {
12+
throw new \InvalidArgumentException(
13+
sprintf(
14+
'The resolver arguments must be of type callable, %s given.',
15+
gettype($resolver)
16+
)
17+
);
18+
}
19+
20+
$this->deferred = new Deferred();
21+
$this->call($resolver);
22+
}
23+
24+
public function then($fulfilledHandler = null, $errorHandler = null, $progressHandler = null)
25+
{
26+
return $this->deferred->then($fulfilledHandler, $errorHandler, $progressHandler);
27+
}
28+
29+
private function call($callback)
30+
{
31+
try {
32+
$callback(
33+
array($this->deferred, 'resolve'),
34+
array($this->deferred, 'reject'),
35+
array($this->deferred, 'progress')
36+
);
37+
} catch (\Exception $e) {
38+
$this->deferred->reject($e);
39+
}
40+
}
41+
}
Lines changed: 67 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,67 @@
1+
<?php
2+
3+
namespace React\Promise;
4+
5+
/**
6+
* @group Promise
7+
*/
8+
class PromiseTest extends TestCase
9+
{
10+
/** @test */
11+
public function shouldThrowIfResolverIsNotACallable()
12+
{
13+
$this->setExpectedException('\InvalidArgumentException');
14+
15+
new Promise(null);
16+
}
17+
18+
/** @test */
19+
public function shouldResolve()
20+
{
21+
$promise = new Promise(function($resolve) {
22+
$resolve(1);
23+
});
24+
25+
$mock = $this->createCallableMock();
26+
$mock
27+
->expects($this->once())
28+
->method('__invoke')
29+
->with($this->identicalTo(1));
30+
31+
$promise->then($mock);
32+
}
33+
34+
/** @test */
35+
public function shouldReject()
36+
{
37+
$promise = new Promise(function($_, $reject) {
38+
$reject(1);
39+
});
40+
41+
$mock = $this->createCallableMock();
42+
$mock
43+
->expects($this->once())
44+
->method('__invoke')
45+
->with($this->identicalTo(1));
46+
47+
$promise->then($this->expectCallableNever(), $mock);
48+
}
49+
50+
/** @test */
51+
public function shouldProgres()
52+
{
53+
$promise = new Promise(function($_, $_, $progress) use (&$notify) {
54+
$notify = $progress;
55+
});
56+
57+
$mock = $this->createCallableMock();
58+
$mock
59+
->expects($this->once())
60+
->method('__invoke')
61+
->with($this->identicalTo(1));
62+
63+
$promise->then($this->expectCallableNever(), $this->expectCallableNever(), $mock);
64+
65+
$notify(1);
66+
}
67+
}

0 commit comments

Comments
 (0)