/** * Dispatches an event for the called RPC * * @param \Ratchet\ConnectionInterface $conn * @param string $id * @param string|\Ratchet\Wamp\Topic $topic * @param array $params */ public function onCall(Conn $conn, $id, $topic, array $params) { $topicName = self::getTopicName($topic); $eventPayload = ['connection' => $conn, 'id' => $id, 'connectionData' => $this->_connections[$conn->WAMP->sessionId]]; $event = $this->dispatchEvent('Rachet.WampServer.Rpc', $this, array_merge($eventPayload, ['topicName' => $topicName, 'topic' => $topic, 'params' => $params, 'wampServer' => $this])); if ($event->isStopped()) { $conn->callError($id, $event->result['stop_reason']['error_uri'], $event->result['stop_reason']['desc'], $event->result['stop_reason']['details']); $this->outVerbose('Rachet.WampServer.Rpc.' . $topicName . ' call (' . $id . ') was blocked'); $this->dispatchEvent('Rachet.WampServer.RpcBlocked', $this, array_merge($eventPayload, ['topicName' => $topicName, 'reason' => $event->result['stop_reason']])); return false; } $start = microtime(true); $deferred = new \React\Promise\Deferred(); $deferred->promise()->then(function ($results) use($conn, $id, $topicName, $start, $eventPayload) { $end = microtime(true); $conn->callResult($id, $results); $this->outVerbose('Rachet.WampServer.Rpc.' . $topicName . ' call (' . $id . ') took <info>' . ($end - $start) . 's</info> and succeeded'); $this->dispatchEvent('Rachet.WampServer.RpcSuccess', $this, array_merge($eventPayload, ['topicName' => $topicName, 'results' => $results])); }, function ($errorUri, $desc = '', $details = null) use($conn, $id, $topicName, $start, $eventPayload) { $end = microtime(true); $conn->callError($id, $errorUri, $desc, $details); $this->outVerbose('Rachet.WampServer.Rpc.' . $topicName . ' call (' . $id . ') took <info>' . ($end - $start) . 's</info> and failed'); $this->dispatchEvent('Rachet.WampServer.RpcFailed', $this, array_merge($eventPayload, ['topicName' => $topicName, 'reason' => [$errorUri, $desc, $details]])); }); $this->dispatchEvent('Rachet.WampServer.Rpc.' . $topicName, $this, array_merge($eventPayload, ['promise' => $deferred, 'topic' => $topic, 'params' => $params, 'wampServer' => $this])); }
/** * @param InputInterface $input * @param OutputInterface $output * @return int */ protected function execute(InputInterface $input, OutputInterface $output) { $loop = \React\EventLoop\Factory::create(); $factory = new \BitWasp\Bitcoin\Networking\Factory($loop); $dns = $factory->getDns(); $peerFactory = $factory->getPeerFactory($dns); $timeout = $input->getOption('timeout'); $host = $peerFactory->getAddress($input->getArgument('host')); $deferred = new \React\Promise\Deferred(); $peer = $peerFactory->getPeer(); $peer->on('version', function (Peer $peer, Version $ver) use($deferred) { $deferred->resolve([$peer, $ver]); }); $deferred->promise()->then(function ($arr) use($loop, $output, &$userHost) { list(, $msg) = $arr; $loop->stop(); $this->renderVersion($output, $userHost, $msg); }); $loop->addPeriodicTimer($timeout, function (Timer $timer) use($loop, $output, &$userHost) { $loop->stop(); $timer->cancel(); $this->renderTimeout($output, $userHost); }); $peer->connect($peerFactory->getConnector(), $host); $loop->run(); return 0; }
/** * @inheritDoc */ public function preProcessAuthenticate(array $args) { if (!isset($args[0]) && !is_object($args[0])) { return ["FAILURE"]; } $authInfo = $args[0]; if (isset($authInfo->authid) && isset($authInfo->signature)) { // lookup the user $query = (new \React\MySQL\Query("SELECT id FROM users WHERE login = ? AND password = ?"))->bindParams($authInfo->authid, $authInfo->signature); $deferred = new \React\Promise\Deferred(); $this->mysqlConnection->query($query->getSql(), function ($command, $conn) use($deferred) { if ($command->hasError()) { //test whether the query was executed successfully //error $error = $command->getError(); // get the error object, instance of Exception. $this->resolve(['FAILURE']); } else { $results = $command->resultRows; //get the results $fields = $command->resultFields; // get table fields if (count($results) > 0) { $deferred->resolve(['SUCCESS']); } else { $deferred->resolve(['FAILURE']); } } }); return $deferred->promise(); } return ["FAILURE"]; }
public function theFunction() { $futureResult = new \React\Promise\Deferred(); $this->getCaller()->call($this->session, 'com.example.thefunction' . ($this->number + 1), array())->then(function ($res) use($futureResult) { $res[0] = $res[0] . "."; $futureResult->resolve($res); }); return $futureResult->promise(); }
public function callFailure() { $deferred = new \React\Promise\Deferred(); //$deferred->reject("Call has failed :("); $this->getLoop()->addTimer(0, function () use($deferred) { $deferred->reject("Call has failed :("); }); return $deferred->promise(); }
public function createTickPromise($value = NULL, $numTicks = 1) { $d = new React\Promise\Deferred(); $this->onTick[] = function () use($value, &$numTicks, $d) { if (--$numTicks === 0) { $d->resolve($value); } }; return $d; }
public function callPublish($args) { $deferred = new \React\Promise\Deferred(); $this->getPublisher()->publish($this->session, "com.example.publish", [$args[0]], ["key1" => "test1", "key2" => "test2"], ["acknowledge" => true])->then(function () use($deferred) { $deferred->resolve('ok'); }, function ($error) use($deferred) { $deferred->reject("failed: {$error}"); }); return $deferred->promise(); }
public function thePartitionedRPC2($args) { $this->_result .= "[start 2(" . $args[0] . ")]"; $deferred = new \React\Promise\Deferred(); $loop = $this->_conn->getClient()->getLoop(); $loop->addTimer(1, function () use($deferred, $args) { $deferred->resolve("[RPC 2(" . $args[0] . ")]"); }); return $deferred->promise(); }
public function __construct() { parent::__construct(function () { $loop = LoopFactory::create(); $context = new ZmqContext($loop); $socket = $context->getSocket(\ZMQ::SOCKET_REP); $socket->bind("tcp://127.0.0.1:5591"); $workers = $context->getSocket(\ZMQ::SOCKET_PUSH); $workers->bind('tcp://127.0.0.1:5592'); $sub = $context->getSocket(\ZMQ::SOCKET_SUB); $sub->connect('tcp://127.0.0.1:5594'); $sub->subscribe('control'); $sub->on('messages', function ($msg) use($loop) { if ($msg[1] == 'shutdown') { $loop->stop(); } }); /** * @var \React\Promise\Deferred[] */ $deferredSet = []; $results = []; $socket->on('message', function ($message) use($socket, $workers, &$results, &$deferredSet) { // Incoming work. Distribute. $payload = json_decode($message, true); $batch = []; $work = ["txid" => $payload['txid'], "tx" => $payload['tx'], "flags" => $payload['flags'], "vin" => null, "scriptPubKey" => null]; // Send to workers, and create a Promise for each result. foreach ($payload['scripts'] as $vin => $scriptPubKey) { $work['vin'] = $vin; $work['scriptPubKey'] = $scriptPubKey; $deferred = new \React\Promise\Deferred(); $deferredSet[$payload['txid'] . $vin] = $deferred; $batch[] = $deferred->promise(); $workers->send(json_encode($work)); } // Once all promises have resolved, return outcome to socket. \React\Promise\all($batch)->then(function ($results) use($socket) { $final = true; foreach ($results as $result) { $final &= $result['result']; } $socket->send($final); }); }); $results = $context->getSocket(\ZMQ::SOCKET_PULL); $results->bind("tcp://127.0.0.1:5593"); $results->on('message', function ($message) use(&$deferredSet) { $payload = json_decode($message, true); $deferredSet[$payload['txid'] . $payload['vin']]->resolve($payload); }); $loop->run(); exit(0); }); }
/** * Handle for RPC 'com.example.thefunction{$number}' * * @return \React\Promise\Promise */ public function theFunction() { $futureResult = new \React\Promise\Deferred(); $this->session->call('com.example.thefunction' . ($this->number + 1), [])->then(function ($res) use($futureResult) { if (is_scalar($res[0])) { $res[0] = $res[0] . "."; } $futureResult->resolve($res[0]); }); return $futureResult->promise(); }
public function test_react_2() { $deferred = new \React\Promise\Deferred(); $promise = $deferred->promise()->then(function ($value) { sleep(5); echo "hhaha 1" . $value; })->then(function ($value) { sleep(3); echo "hhaha 2" . $value; })->then(function ($value) { echo "hhaha 3" . $value; }); $deferred->resolve('abc'); }
* @var \React\Promise\Deferred[] */ $socket->on('message', function ($message) use($socket, $workers, &$results, &$deferredSet) { // Incoming work. Distribute. $payload = json_decode($message, true); $reqid = $payload['id']; $batch = []; $work = ["txid" => null, "tx" => null, "flags" => $payload['flags'], "vin" => null, "scriptPubKey" => null]; // Send to workers, and create a Promise for each result. foreach ($payload['txs'] as $t) { $work['txid'] = $t['txid']; $work['tx'] = $t['tx']; foreach ($t['scripts'] as $vin => $scriptPubKey) { $work['vin'] = $vin; $work['scriptPubKey'] = $scriptPubKey; $deferred = new \React\Promise\Deferred(); $deferredSet[$t['txid'] . $vin] = $deferred; $batch[] = $deferred->promise(); $workers->send(json_encode($work)); } } // Once all promises have resolved, return outcome to socket. \React\Promise\all($batch)->then(function ($results) use($socket, $reqid) { $final = true; foreach ($results as $result) { $final &= $result; } $socket->send(json_encode(['txid' => $reqid, 'result' => $final])); }); }); $loop->run();
<?php require 'vendor/autoload.php'; $i = 0; $loop = \React\EventLoop\Factory::create(); $deferred = new \React\Promise\Deferred(); $timer = $loop->addPeriodicTimer(0.01, function (\React\EventLoop\Timer\Timer $timer) use(&$i, $deferred) { $deferred->notify($i++); if ($i >= 66) { $timer->cancel(); $deferred->resolve(); } }); $deferred->promise()->then(function ($i) { echo 'Done!', PHP_EOL; }, null, function ($i) { echo $i, PHP_EOL; }); $loop->run();
<?php require_once "../vendor/autoload.php"; use BitWasp\Bitcoin\Networking\Peer\Peer; $loop = React\EventLoop\Factory::create(); $factory = new \BitWasp\Bitcoin\Networking\Factory($loop); $peerFactory = $factory->getPeerFactory($factory->getDns()); $host = $peerFactory->getAddress('147.87.116.162'); $local = $peerFactory->getAddress('192.168.192.39'); $deferred = new \React\Promise\Deferred(); $peer = $peerFactory->getPeer(); $peer->on('version', function (Peer $peer, \BitWasp\Bitcoin\Networking\Messages\Version $ver) use($deferred) { $deferred->resolve($ver); }); $peer->on('ready', function (Peer $peer) use($factory) { $peer->close(); }); $connector = $peerFactory->getConnector(); $peer->requestRelay()->connect($connector, $host); $deferred->promise()->then(function ($msg) use($loop) { print_r($msg); $loop->stop(); }); $loop->run();
//echo $x . "\n"; $messages->onNext($x); }, [$messages, "onError"], [$messages, "onCompleted"])); }, function ($error) use($case, $deferred) { echo "Error on " . $case . "\n"; $deferred->reject($error); }, function () use($case, $deferred) { echo "Finished " . $case . "\n"; $deferred->resolve(); })); return $deferred->promise(); }; $runTests = function ($testCount) use($runIndividualTest, $runReports) { echo "Server would like us to run " . $testCount . " tests.\n"; $i = 0; $deferred = new \React\Promise\Deferred(); $runNextCase = function () use(&$i, &$runNextCase, $testCount, $deferred, $runIndividualTest) { $i++; if ($i > $testCount) { $deferred->resolve(); return; } $runIndividualTest($i)->then($runNextCase); }; $runNextCase(); $deferred->promise()->then($runReports); }; // get the tests that need to run $client = new \Rx\Websocket\Client("ws://127.0.0.1:9001/getCaseCount"); $client->flatMap(function ($x) { return $x;
/** * @dataProvider testOnCallBlockProvider */ public function testOnCallBlock($topic) { $topicName = (string) $topic; $mock = $this->getMock('\\Ratchet\\ConnectionInterface', ['send', 'close']); $deferred = new \React\Promise\Deferred(); $deferred->promise()->then(function ($results) { }, function ($results) { }); $conn = $this->getMock('\\Ratchet\\Wamp\\WampConnection', ['callError'], [$mock]); $blockReason = ['error_uri' => 1, 'desc' => 2, 'details' => 3]; $conn->expects($this->once())->method('callError')->with(1, $blockReason['error_uri'], $blockReason['desc'], $blockReason['details']); $conn->Session = new SessionHandlerImposer(); $asserts = []; $this->_expectedEventCalls($asserts, ['Rachet.WampServer.Rpc' => ['callback' => [function ($event) use($blockReason) { $event->result['stop_reason'] = $blockReason; $event->stopPropagation(); }]], 'Rachet.WampServer.RpcBlocked' => ['callback' => [function ($event) use($conn, $topicName, $topic, $blockReason) { $this->assertEquals($event->data, ['topicName' => $topicName, 'connection' => $conn, 'id' => 1, 'reason' => $blockReason, 'connectionData' => ['topics' => [], 'session' => []]]); }]]]); $this->AppServer->onOpen($conn); $this->AppServer->onCall($conn, 1, $topic, ['foo' => 'bar']); foreach ($asserts as $assert) { $this->assertTrue($assert); } }
#!/usr/bin/php <?php $config = ['git_urls' => ['https://github.com/yfix/promise.git' => 'promise/'], 'autoload_config' => ['promise/src/' => 'React\\Promise'], 'require_once' => ['promise/src/functions.php'], 'example' => function () { $deferred = new \React\Promise\Deferred(); $promise = $deferred->promise(); var_dump($promise); }]; if ($return_config) { return $config; } require_once __DIR__ . '/_yf_autoloader.php'; new yf_autoloader($config);
/** * @param callable $wait * @param callable|null $cancel * @return \GuzzleHttp\Message\FutureResponse */ private function createFuture(callable $wait, callable $cancel = null) { $deferred = new \React\Promise\Deferred(); return new \GuzzleHttp\Message\FutureResponse($deferred->promise(), function () use($deferred, $wait) { $deferred->resolve($wait()); }, $cancel); }
/** * @return \React\Promise\Promise */ public function perform() { $instance = $this->getInstance(); $deferred = new \React\Promise\Deferred(); $promise = $deferred->promise(); $promise->then(function () { $this->worker->processing++; }); if (method_exists($instance, 'setUp')) { $promise = $promise->then(function () use($instance) { return \React\Promise\resolve($instance->setUp()); }); } $promise = $promise->then(function () use($instance) { return $instance->perform(); }); if (method_exists($instance, 'tearDown')) { $promise = $promise->then(function ($response = null) use($instance) { return \React\Promise\resolve($instance->tearDown()); }); } $promise->then(function ($responses = null) { $this->worker->processing--; $this->worker->processed++; }, function ($e) { $this->worker->processing--; $this->worker->processed++; if ($e instanceof \Exception) { error_log(sprintf('%s:%s in %s at %d', get_class($e), $e->getMessage(), __FILE__, __LINE__)); } error_log($e); }); $deferred->resolve(); return $promise; }
public function callReturnSomeProgress($args, $argsKw, $details) { if (is_array($details) && isset($details['receive_progress']) && $details['receive_progress']) { $deferred = new \React\Promise\Deferred(); $this->getLoop()->addTimer(1, function () use($deferred) { $deferred->progress(1); }); $this->getLoop()->addTimer(2, function () use($deferred) { $deferred->progress(2); }); $this->getLoop()->addTimer(3, function () use($deferred) { $deferred->resolve("DONE"); }); return $deferred->promise(); } else { throw new \Exception("receive_progress option not set"); } }