promise() public method

public promise ( )
Example #1
0
 public function run()
 {
     $this->deferred = new Deferred();
     $this->deferred->promise()->progress(function ($event) {
         $this->data[$event['part']] = $event['data'];
         unset($this->unsettled[$event['part']]);
         if ($this->isEverythingHasBeenReceived()) {
             $this->deferred->resolve();
         }
     })->then(function () {
         if (isset($this->cancel_timer)) {
             $this->loop->cancelTimer($this->cancel_timer);
             unset($this->cancel_timer);
         }
     })->done(function () {
         $response = call_user_func($this->then_callback, $this->data);
         $headers = ['Content-Type' => 'text/plain'];
         $this->response->writeHead(200, $headers);
         $this->response->end($response);
     }, function () {
         $headers = ['Content-Type' => 'text/plain'];
         $this->response->writeHead(404, $headers);
         $this->response->end("Failed");
     });
     if (empty($this->requests)) {
         $this->deferred->resolve();
     } else {
         $this->registerCancelTimer();
         foreach ($this->requests as $request) {
             $request->end();
         }
     }
     return $this;
 }
Example #2
0
 private function collectEvents($command, $expectedEndEvent)
 {
     $req = $this->client->createAction($command);
     $ret = $this->client->request($req);
     $id = $req->getActionId();
     $deferred = new Deferred();
     // collect all intermediary channel events with this action ID
     $collected = array();
     $collector = function (Event $event) use($id, &$collected, $deferred, $expectedEndEvent) {
         if ($event->getActionId() === $id) {
             $collected[] = $event;
             if ($event->getName() === $expectedEndEvent) {
                 $deferred->resolve($collected);
             }
         }
     };
     $this->client->on('event', $collector);
     // unregister collector if client fails
     $client = $this->client;
     $unregister = function () use($client, $collector) {
         $client->removeListener('event', $collector);
     };
     $ret->then(null, $unregister);
     // stop waiting for events
     $deferred->promise()->then($unregister);
     return $ret->then(function (Response $response) use($deferred) {
         // final result has been received => merge all intermediary channel events
         return $deferred->promise()->then(function ($collected) use($response) {
             $last = array_pop($collected);
             return new Collection($response, $collected, $last);
         });
     });
 }
Example #3
0
 /**
  * {@inheritdoc}
  */
 public function start()
 {
     if (isset($this->deferred)) {
         throw new \RuntimeException('Tasks is already started');
     }
     $this->deferred = new Deferred();
     return $this->deferred->promise();
 }
Example #4
0
 /**
  * The option values for 'before', 'complete', 'error' and 'end' can be a
  * callable, an associative array containing event data, or an array of
  * event data arrays. Event data arrays contain the following keys:
  *
  * - fn: callable to invoke that receives the event
  * - priority: Optional event priority (defaults to 0)
  * - once: Set to true so that the event is removed after it is triggered
  *
  * @param ClientInterface $client   Client used to send the requests.
  * @param array|\Iterator $requests Requests to send in parallel
  * @param array           $options  Associative array of options
  *     - pool_size: (callable|int)   Maximum number of requests to send
  *                                   concurrently, or a callback that receives
  *                                   the current queue size and returns the
  *                                   number of new requests to send
  *     - before:    (callable|array) Receives a BeforeEvent
  *     - complete:  (callable|array) Receives a CompleteEvent
  *     - error:     (callable|array) Receives a ErrorEvent
  *     - end:       (callable|array) Receives an EndEvent
  */
 public function __construct(ClientInterface $client, $requests, array $options = [])
 {
     $this->client = $client;
     $this->iter = $this->coerceIterable($requests);
     $this->deferred = new Deferred();
     $this->promise = $this->deferred->promise();
     $this->poolSize = isset($options['pool_size']) ? $options['pool_size'] : 25;
     $this->eventListeners = $this->prepareListeners($options, ['before', 'complete', 'error', 'end']);
 }
Example #5
0
 /**
  * {@inheritdoc}
  */
 public function start()
 {
     if (isset($this->deferred)) {
         throw new \RuntimeException('Tasks is already started');
     }
     $this->deferred = new Deferred();
     $this->process->start(function () {
         $this->outputBuffer->enqueue(func_get_args());
     });
     return $this->deferred->promise();
 }
Example #6
0
 /**
  * Call curl_multi_add_handle().
  * @param resource $ch
  * @return PromiseInterface
  */
 public function add($ch)
 {
     $deferred = new Deferred();
     $errno = curl_multi_add_handle($this->mh, $ch);
     if ($errno !== CURLM_OK) {
         // @codeCoverageIgnoreStart
         $msg = curl_multi_strerror($errno) . ": {$ch}";
         $deferred->reject(new \RuntimeException($msg));
         return $deferred->promise();
         // @codeCoverageIgnoreEnd
     }
     $this->added[(string) $ch] = $ch;
     $this->deferreds[(string) $ch] = $deferred;
     return $deferred->promise();
 }
Example #7
0
 public function search($searchTarget = 'ssdp:all', $mx = 2)
 {
     $data = "M-SEARCH * HTTP/1.1\r\n";
     $data .= "HOST: " . self::ADDRESS . "\r\n";
     $data .= "MAN: \"ssdp:discover\"\r\n";
     $data .= "MX: {$mx}\r\n";
     $data .= "ST: {$searchTarget}\r\n";
     $data .= "\r\n";
     $socket = $this->multicast->createSender();
     // TODO: The TTL for the IP packet SHOULD default to 2 and SHOULD be configurable.
     $timer = $this->loop->addTimer($mx, function () use($socket, &$deferred) {
         $deferred->resolve();
         $socket->close();
     });
     $deferred = new Deferred(function () use($socket, &$timer) {
         // canceling resulting promise cancels timer and closes socket
         $timer->cancel();
         $socket->close();
         throw new RuntimeException('Cancelled');
     });
     $that = $this;
     $socket->on('message', function ($data, $remote) use($deferred, $that) {
         $message = $that->parseMessage($data, $remote);
         $deferred->progress($message);
     });
     $socket->send($data, self::ADDRESS);
     return $deferred->promise();
 }
Example #8
0
 public function loadEtcResolvConf($filename)
 {
     if (!file_exists($filename)) {
         return When::reject(new \InvalidArgumentException("The filename for /etc/resolv.conf given does not exist: {$filename}"));
     }
     try {
         $deferred = new Deferred();
         $fd = fopen($filename, 'r');
         stream_set_blocking($fd, 0);
         $contents = '';
         $stream = new Stream($fd, $this->loop);
         $stream->on('data', function ($data) use(&$contents) {
             $contents .= $data;
         });
         $stream->on('end', function () use(&$contents, $deferred) {
             $deferred->resolve($contents);
         });
         $stream->on('error', function ($error) use($deferred) {
             $deferred->reject($error);
         });
         return $deferred->promise();
     } catch (\Exception $e) {
         return When::reject($e);
     }
 }
Example #9
0
 /**
  * Connect to $numSeeds DNS seeds
  *
  * @param int $numSeeds
  * @return \React\Promise\Promise|\React\Promise\PromiseInterface
  */
 public function queryDnsSeeds($numSeeds = 1)
 {
     $peerList = new Deferred();
     // Take $numSeeds
     $seedHosts = self::dnsSeedHosts();
     $seeds = array_slice($seedHosts, 0, min($numSeeds, count($seedHosts)));
     // Connect to $numSeeds peers
     /** @var Peer[] $vNetAddr */
     $vNetAddr = [];
     foreach ($seeds as $seed) {
         echo " [ query DNS seed: " . $seed . " ] \n";
         $this->dns->resolve($seed)->then(function ($ipList) use(&$vNetAddr, $peerList, &$numSeeds) {
             $vNetAddr[] = $ipList;
             if (count($vNetAddr) == $numSeeds) {
                 $peerList->resolve($vNetAddr);
             }
         });
     }
     // Compile the list of lists of peers into $this->knownAddresses
     return $peerList->promise()->then(function (array $vPeerVAddrs) {
         shuffle($vPeerVAddrs);
         /** @var NetworkAddressInterface[] $addresses */
         $addresses = [];
         array_map(function (array $value) use(&$addresses) {
             foreach ($value as $ip) {
                 $addresses[] = new NetworkAddress(Buffer::hex('01', 8), $ip, 8333);
             }
         }, $vPeerVAddrs);
         $this->knownAddresses = array_merge($this->knownAddresses, $addresses);
         return $this;
     });
 }
Example #10
0
 /** @internal */
 public function go(Process $process)
 {
     $this->deferred = $deferred = new Deferred();
     $this->process = $process;
     $buffered = null;
     $process->stdout->on('data', function ($data) use(&$buffered) {
         if ($data !== '') {
             $buffered .= $data;
         }
     });
     $process->on('exit', function ($code) use($deferred) {
         if ($code !== 0) {
             $deferred->reject($code);
         } else {
             $deferred->resolve();
         }
     });
     $that = $this;
     $this->promise = $deferred->promise()->then(function () use(&$buffered, $that) {
         if ($buffered === null) {
             $buffered = true;
         } else {
             $buffered = $that->parseValue(trim($buffered));
         }
         return $buffered;
     });
 }
 protected function createInternalAsync($host, $docroot, $router)
 {
     $deferred = new Deferred();
     $process = new BuiltinServer($host, $docroot, $router, $this->php);
     $process->start($this->loop);
     $process->on('exit', function ($code) use($deferred) {
         $this->stderr->write("Process exit with code {$code}\n");
         $deferred->reject();
     });
     $process->stdin->close();
     $process->stdout->close();
     $process->stderr->on('data', function ($output) use($deferred) {
         $this->stderr->write($output);
         $deferred->reject();
     });
     $timer = new Deferred();
     $this->loop->addTimer(0.05, function () use($timer, $process) {
         if (DIRECTORY_SEPARATOR === '\\') {
             // Pipes opened by proc_open() can break stream_select() loop in Windows.
             // This fix might do the trick...
             $process->stderr->close();
         }
         $timer->resolve($process);
     });
     return \React\Promise\race([$deferred->promise(), $timer->promise()])->then(null, function () use($process) {
         $process->terminate();
         return new RejectedPromise();
     });
 }
Example #12
0
 /**
  * @expectedException \RuntimeException
  */
 public function testThrowsWhenAccessingInvalidProperty()
 {
     $deferred = new Deferred();
     $f = new FutureArray($deferred->promise(), function () {
     });
     $f->foo;
 }
Example #13
0
 /**
  * @param $channel
  * @param string $message
  * @return DeferredPromise
  */
 public function call($channel, $message)
 {
     $loop = LoopFactory::create();
     $factory = new StompFactory($loop);
     $client = $factory->createClient();
     $deferred = new Deferred();
     $timer = $loop->addTimer(2, function () use($deferred, $client) {
         $client->disconnect();
         $deferred->reject(new RpcTimeIsOutException());
     });
     $client->connect()->then(function (StompClient $client) use($message, $channel, $loop, $deferred, $timer) {
         $rpcReceiver = function (Frame $frame) use($deferred, $timer, $client) {
             $timer->cancel();
             $client->disconnect();
             try {
                 $deferred->resolve($frame);
             } catch (\Exception $e) {
                 $deferred->reject($e);
             }
         };
         $client->sendToTemp($channel, $message, [], $rpcReceiver);
     }, function () use($deferred, $client) {
         $client->disconnect();
         $deferred->reject(new \RuntimeException('Error start rpc connection'));
     });
     $loop->run();
     return $deferred->promise();
 }
 /**
  * @returns \React\Promise\Promise
  */
 public function show()
 {
     $deferred = new Deferred();
     $this->io->out('hello');
     $deferred->reject(false);
     return $deferred->promise();
 }
Example #15
0
 public function doQuery($nameserver, $transport, $queryData, $name)
 {
     $parser = $this->parser;
     $loop = $this->loop;
     $response = new Message();
     $deferred = new Deferred();
     $retryWithTcp = function () use($nameserver, $queryData, $name) {
         return $this->doQuery($nameserver, 'tcp', $queryData, $name);
     };
     $timer = $this->loop->addTimer($this->timeout, function () use(&$conn, $name, $deferred) {
         $conn->close();
         $deferred->reject(new TimeoutException(sprintf("DNS query for %s timed out", $name)));
     });
     $conn = $this->createConnection($nameserver, $transport);
     $conn->on('data', function ($data) use($retryWithTcp, $conn, $parser, $response, $transport, $deferred, $timer) {
         $responseReady = $parser->parseChunk($data, $response);
         if (!$responseReady) {
             return;
         }
         $timer->cancel();
         if ($response->header->isTruncated()) {
             if ('tcp' === $transport) {
                 $deferred->reject(new BadServerException('The server set the truncated bit although we issued a TCP request'));
             } else {
                 $conn->end();
                 $deferred->resolve($retryWithTcp());
             }
             return;
         }
         $conn->end();
         $deferred->resolve($response);
     });
     $conn->write($queryData);
     return $deferred->promise();
 }
Example #16
0
 public static function createFuture(callable $wait, callable $cancel = null)
 {
     $deferred = new Deferred();
     return new FutureResponse($deferred->promise(), function () use($deferred, $wait) {
         $deferred->resolve($wait());
     }, $cancel);
 }
Example #17
0
 /**
  * @param Request $request
  * @return \React\Promise\Promise|\React\Promise\PromiseInterface
  */
 public function sendRequest(Request $request)
 {
     $result = new Deferred();
     $this->deferred[$request->getId()] = $result;
     $this->sendData($request->write());
     return $result->promise();
 }
 private function executeRequest($method, $uri, $body = null)
 {
     $deferred = new Deferred();
     $request = $this->client->request($method, $this->buildUrl($uri), array('Content-Length' => strlen($body), 'Authorization' => 'Basic ' . base64_encode($this->options['user'] . ':' . $this->options['password']), 'Content-Type' => 'application/json'));
     $request->writeHead();
     $request->on('error', function ($error) use($uri, $deferred) {
         $deferred->reject(sprintf('Error while doing the request on %s : %s', $uri, $error->getMessage()));
     });
     $request->on('response', function (Response $response) use($deferred) {
         if ($response->getCode() < 200 || $response->getCode() >= 400) {
             $deferred->reject(sprintf('The response is not as expected (status code %s, message is %s)', $response->getCode(), $response->getReasonPhrase()));
         }
         $response->on('error', function ($error) use($deferred) {
             $deferred->reject($error->getMessage());
         });
         $data = (object) array('data' => '');
         $response->on('data', function ($chunk) use($data) {
             $data->data .= $chunk;
         });
         $response->on('end', function () use($deferred, $data) {
             $deferred->resolve($data->data);
         });
     });
     $request->end($body);
     return $deferred->promise();
 }
Example #19
0
 protected function createPromiseRejected($value = null, $delay = 0.01)
 {
     $deferred = new Deferred();
     $this->loop->addTimer($delay, function () use($deferred, $value) {
         $deferred->reject($value);
     });
     return $deferred->promise();
 }
Example #20
0
 /**
  * @expectedException \Exception
  * @expectedExceptionMessage foo
  */
 public function testThrowingExceptionInDerefMarksAsFailed()
 {
     $deferred = new Deferred();
     $f = new FutureValue($deferred->promise(), function () {
         throw new \Exception('foo');
     });
     $f->wait();
 }
 protected function createConnectionManagerMock($ret)
 {
     $mock = $this->getMockBuilder('React\\SocketClient\\Connector')->disableOriginalConstructor()->getMock();
     $deferred = new Deferred();
     $deferred->resolve($ret);
     $mock->expects($this->any())->method('create')->will($this->returnValue($deferred->promise()));
     return $mock;
 }
Example #22
0
 public function start()
 {
     $deferred = new Deferred();
     $this->loop->addTimer($this->interval, function () use($deferred) {
         $deferred->resolve();
     });
     return $deferred->promise();
 }
 /**
  * @return \React\Promise\Promise
  */
 protected function perform()
 {
     $this->deferred = new Deferred();
     $this->loop->addTimer((int) $this->options['delay'] / 1000, function () {
         $this->tickRequest();
     });
     return $this->deferred->promise();
 }
Example #24
0
 public function __invoke($url, array $subProtocols = [], array $headers = [])
 {
     try {
         $request = $this->generateRequest($url, $subProtocols, $headers);
     } catch (\Exception $e) {
         return new RejectedPromise($e);
     }
     $connector = 'wss' === substr($url, 0, 3) ? $this->_secureConnector : $this->_connector;
     return $connector->create($request->getHost(), $request->getPort())->then(function (DuplexStreamInterface $stream) use($request, $subProtocols) {
         $futureWsConn = new Deferred();
         $buffer = '';
         $headerParser = function ($data, DuplexStreamInterface $stream) use(&$headerParser, &$buffer, $futureWsConn, $request, $subProtocols) {
             $buffer .= $data;
             if (false == strpos($buffer, "\r\n\r\n")) {
                 return;
             }
             $stream->removeListener('data', $headerParser);
             $response = Response::fromMessage($buffer);
             if (101 !== $response->getStatusCode()) {
                 $futureWsConn->reject($response);
                 $stream->close();
                 return;
             }
             $acceptCheck = base64_encode(pack('H*', sha1($request->getHeader('Sec-WebSocket-Key') . RFC6455::GUID)));
             if ((string) $response->getHeader('Sec-WebSocket-Accept') !== $acceptCheck) {
                 $futureWsConn->reject(new \DomainException("Could not verify Accept Key during WebSocket handshake"));
                 $stream->close();
                 return;
             }
             $acceptedProtocol = $response->getHeader('Sec-WebSocket-Protocol');
             if ((count($subProtocols) > 0 || null !== $acceptedProtocol) && !in_array((string) $acceptedProtocol, $subProtocols)) {
                 $futureWsConn->reject(new \DomainException('Server did not respond with an expected Sec-WebSocket-Protocol'));
                 $stream->close();
                 return;
             }
             $futureWsConn->resolve(new WebSocket($stream, $response, $request));
             $futureWsConn->promise()->then(function (WebSocket $conn) use($stream) {
                 $stream->emit('data', [$conn->response->getBody(), $stream]);
             });
         };
         $stream->on('data', $headerParser);
         $stream->write($request);
         return $futureWsConn->promise();
     });
 }
 /**
  * @param Rpc $message
  * @return PromiseInterface
  */
 public function rpc(Rpc $message)
 {
     $hash = spl_object_hash($message);
     $deferred = new Deferred();
     $this->deferreds[$hash] = $deferred;
     $this->queue->enqueue($message);
     $this->manager->ping();
     return $deferred->promise();
 }
 public function promiseAction(Request $request)
 {
     $secs = intval($request->attributes->get("secs"));
     $deferred = new Deferred();
     $this->loop->addTimer($secs, function () use($secs, $deferred) {
         $deferred->resolve(Response::create("{$secs} seconds later...\n"));
     });
     return $deferred->promise();
 }
Example #27
0
 /** @test */
 public function progressIsAnAliasForNotify()
 {
     $deferred = new Deferred();
     $sentinel = new \stdClass();
     $mock = $this->createCallableMock();
     $mock->expects($this->once())->method('__invoke')->with($sentinel);
     $deferred->promise()->then($this->expectCallableNever(), $this->expectCallableNever(), $mock);
     $deferred->progress($sentinel);
 }
Example #28
0
 public function getPromiseTestAdapter(callable $canceller = null)
 {
     $d = new Deferred($canceller);
     $factory = function () use($d) {
         return $d->promise();
     };
     return new CallbackPromiseAdapter(['promise' => function () use($factory) {
         return new LazyPromise($factory);
     }, 'resolve' => [$d, 'resolve'], 'reject' => [$d, 'reject'], 'settle' => [$d, 'resolve']]);
 }
Example #29
0
 protected function waitForStreamOnce($stream)
 {
     $deferred = new Deferred();
     $loop = $this->loop;
     $this->loop->addWriteStream($stream, function ($stream) use($loop, $deferred) {
         $loop->removeWriteStream($stream);
         $deferred->resolve($stream);
     });
     return $deferred->promise();
 }
 public function start()
 {
     $command = $this->getCommand($this->keys);
     $deferred = new Deferred();
     $command->start($this->loop, 0.001);
     $command->on('exit', function () use($deferred) {
         $deferred->resolve();
     });
     return $deferred->promise();
 }