Skip to content

Commit 57f3696

Browse files
authored
Merge pull request #31 from samuelnogueira/react_promise_interop
Improve interoperability with reactphp/promise
2 parents 3671060 + 81f96ac commit 57f3696

File tree

2 files changed

+25
-1
lines changed

2 files changed

+25
-1
lines changed

src/Promise.php

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -81,7 +81,9 @@ public function then(callable $onFulfilled = null, callable $onRejected = null)
8181

8282
$this->onFulfilled = function (ResponseInterface $response) use ($onFulfilled, $newPromise) {
8383
try {
84-
$newPromise->resolve($onFulfilled($response));
84+
$return = $onFulfilled($response);
85+
86+
$newPromise->resolve(null !== $return ? $return : $response);
8587
} catch (Exception $exception) {
8688
$newPromise->reject($exception);
8789
}

tests/PromiseTest.php

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@
66
use Http\Adapter\React\Promise;
77
use Http\Adapter\React\ReactFactory;
88
use PHPUnit\Framework\TestCase;
9+
use Psr\Http\Message\ResponseInterface;
910

1011
class PromiseTest extends TestCase
1112
{
@@ -31,4 +32,25 @@ public function testChain()
3132
self::assertEquals(200, $response->getStatusCode());
3233
self::assertEquals(300, $updatedResponse->getStatusCode());
3334
}
35+
36+
public function testOnFulfilledOptionalReturn()
37+
{
38+
$promise = new Promise($this->loop);
39+
$response = new Response(200);
40+
41+
// create a random mock so we can assert $onFulfilled is called with the correct response
42+
/** @var \SplObjectStorage|\PHPUnit_Framework_MockObject_MockObject $mock */
43+
$mock = $this->getMockBuilder(\SplObjectStorage::class)->getMock();
44+
$mock->expects(self::once())->method('attach')->with($response);
45+
46+
$lastPromise = $promise->then(function (ResponseInterface $response) use ($mock) {
47+
$mock->attach($response);
48+
});
49+
50+
$promise->resolve($response);
51+
$lastResponse = $lastPromise->wait();
52+
53+
// even though our $onFulfilled doesn't return a value, we expect the promise to unwrap the original response
54+
self::assertSame($response, $lastResponse);
55+
}
3456
}

0 commit comments

Comments
 (0)