public function get($key) { if (!isset($this->data[$key])) { return Promise\reject(); } return Promise\resolve($this->data[$key]); }
/** * create redis client connected to address of given redis instance * * @param string|null $target * @return \React\Promise\PromiseInterface resolves with Client or rejects with \Exception */ public function createClient($target = null) { try { $parts = $this->parseUrl($target); } catch (InvalidArgumentException $e) { return Promise\reject($e); } $protocol = $this->protocol; $promise = $this->connector->create($parts['host'], $parts['port'])->then(function (Stream $stream) use($protocol) { return new StreamingClient($stream, $protocol->createResponseParser(), $protocol->createSerializer()); }); if (isset($parts['auth'])) { $promise = $promise->then(function (StreamingClient $client) use($parts) { return $client->auth($parts['auth'])->then(function () use($client) { return $client; }, function ($error) use($client) { $client->close(); throw $error; }); }); } if (isset($parts['db'])) { $promise = $promise->then(function (StreamingClient $client) use($parts) { return $client->select($parts['db'])->then(function () use($client) { return $client; }, function ($error) use($client) { $client->close(); throw $error; }); }); } return $promise; }
public function loadEtcResolvConf($filename) { if (!file_exists($filename)) { return Promise\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 Promise\reject($e); } }
/** * Creates a `Promise` which resolves with the first event data * * @param ReadableStreamInterface|WritableStreamInterface $stream * @param string $event * @return CancellablePromiseInterface Promise<mixed, Exception> */ function first(EventEmitterInterface $stream, $event = 'data') { if ($stream instanceof ReadableStreamInterface) { // readable or duplex stream not readable => already closed // a half-open duplex stream is considered closed if its readable side is closed if (!$stream->isReadable()) { return Promise\reject(new \RuntimeException('Stream already closed')); } } elseif ($stream instanceof WritableStreamInterface) { // writable-only stream (not duplex) not writable => already closed if (!$stream->isWritable()) { return Promise\reject(new \RuntimeException('Stream already closed')); } } return new Promise\Promise(function ($resolve, $reject) use($stream, $event, &$listener) { $listener = function ($data) use($stream, $event, &$listener, $resolve) { $stream->removeListener($event, $listener); $resolve($data); }; $stream->on($event, $listener); $stream->on('close', function () use($stream, $event, $listener, $reject) { $stream->removeListener($event, $listener); $reject(new \RuntimeException('Stream closed')); }); }, function ($_, $reject) use($stream, $event, &$listener) { $stream->removeListener($event, $listener); $reject(new \RuntimeException('Operation cancelled')); }); }
/** @test */ public function rejectShouldRejectWithRejectedPromise() { extract($this->getPromiseTestAdapter()); $mock = $this->createCallableMock(); $mock->expects($this->once())->method('__invoke')->with($this->identicalTo(1)); $promise()->then($this->expectCallableNever(), $mock); $reject(Promise\reject(1)); }
public function create($path, $unusedPort = 0) { $resource = @stream_socket_client('unix://' . $path, $errno, $errstr, 1.0); if (!$resource) { return Promise\reject(new RuntimeException('Unable to connect to unix domain socket "' . $path . '": ' . $errstr, $errno)); } return Promise\resolve(new Stream($resource, $this->loop)); }
/** @test */ public function resolveShouldRejectWhenResolvedWithRejectedPromise() { $adapter = $this->getPromiseTestAdapter(); $mock = $this->createCallableMock(); $mock->expects($this->once())->method('__invoke')->with($this->identicalTo(1)); $adapter->promise()->then($this->expectCallableNever(), $mock); $adapter->resolve(Promise\reject(1)); }
public function testWillTryAllIfEachRejects() { $rejected = Promise\reject(new \RuntimeException('nope')); $connector = $this->getMock('React\\SocketClient\\ConnectorInterface'); $connector->expects($this->exactly(2))->method('create')->with('google.com', 80)->willReturn($rejected); $cm = new ConnectionManagerRandom(array($connector, $connector)); $promise = $cm->create('google.com', 80); $this->assertPromiseReject($promise); }
public function testRejectedWillNotStartTimer() { $promise = Promise\reject(); Timer\timeout($promise, 3, $this->loop); $time = microtime(true); $this->loop->run(); $time = microtime(true) - $time; $this->assertLessThan(0.5, $time); }
public function testTwoTriesWillStartTwoConnectionAttempts() { $promise = Promise\reject(new \RuntimeException('nope')); $connector = $this->getMock('React\\SocketClient\\ConnectorInterface'); $connector->expects($this->exactly(2))->method('create')->with('google.com', 80)->willReturn($promise); $cm = new ConnectionManagerRepeat($connector, 2); $promise = $cm->create('google.com', 80); $this->assertPromiseReject($promise); }
/** @internal */ public function checkConnectedSocket($socket) { // The following hack looks like the only way to // detect connection refused errors with PHP's stream sockets. if (false === stream_socket_get_name($socket, true)) { return Promise\reject(new ConnectionException('Connection refused')); } return Promise\resolve($socket); }
public function create($host, $port) { try { $connector = $this->getConnectorForTarget($host, $port); } catch (UnderflowException $e) { return Promise\reject($e); } return $connector->create($host, $port); }
public function testSenderRejection() { $connector = $this->getMock('React\\SocketClient\\ConnectorInterface'); $connector->expects($this->once())->method('create')->willReturn(Promise\reject(new RuntimeException('Rejected'))); $sender = Sender::createFromLoopConnectors($this->loop, $connector); $request = new Request('GET', 'http://www.google.com/'); $promise = $sender->send($request, $this->getMock('Clue\\React\\Buzz\\Message\\MessageFactory')); $this->setExpectedException('RuntimeException'); Block\await($promise, $this->loop); }
/** * @param string $data * @return PromiseInterface * @throws Exception */ public function send($data) { try { $this->connect(); stream_set_blocking($this->sock, true); fwrite($this->sock, $data); return Promise\resolve(); } catch (\Exception $e) { return Promise\reject($e); } }
public function refresh() : PromiseInterface { return $this->getTransport()->request('repos/' . $this->repositoryId() . '/branches')->then(function ($json) { foreach ($json['broadcasts'] as $broadcast) { if ($broadcast['id'] != $this->id()) { continue; } return resolve($this->getTransport()->getHydrator()->hydrate('Broadcast', $broadcast)); } return reject(); }); }
/** * @param RequestInterface $request * * @return PromiseInterface */ public function sendRequest(RequestInterface $request) { if (isset($this->promises[$request->getRequestId()])) { return promise\reject(new ClientException("ID {$request->getRequestId()} already in use")); } $this->responseBuilders[$request->getRequestId()] = new ResponseParser($request->getRequestId()); $this->promises[$request->getRequestId()] = new Deferred(); foreach ($request->toRecords() as $record) { $this->connector->write($record->encode()); } return $this->promises[$request->getRequestId()]->promise(); }
public function refresh() : PromiseInterface { return $this->getTransport()->request('hooks')->then(function ($json) { foreach ($json['hooks'] as $hook) { if ($hook['id'] != $this->id()) { continue; } return resolve($this->getTransport()->getHydrator()->hydrate('Hook', $hook)); } return reject(); }); }
public function lookup(Query $query) { $id = $this->serializeQueryToIdentity($query); $expiredAt = $this->expiredAt; return $this->cache->get($id)->then(function ($value) use($query, $expiredAt) { $recordBag = unserialize($value); if (null !== $expiredAt && $expiredAt <= $query->currentTime) { return Promise\reject(); } return $recordBag->all(); }); }
public function refresh() : PromiseInterface { return $this->getTransport()->request('settings/env_vars?repository_id=' . $this->repositoryId())->then(function ($json) { foreach ($json['env_vars'] as $envVar) { if ($envVar['id'] != $this->id()) { continue; } return resolve($this->getTransport()->getHydrator()->hydrate('EnvironmentVariable', $envVar)); } return reject(); }); }
/** * @return PromiseInterface */ public function refresh() : PromiseInterface { return $this->getTransport()->request('jobs/' . $this->jobId() . '/annotations')->then(function ($json) { foreach ($json['annotations'] as $annotation) { if ($annotation['id'] != $this->id()) { continue; } return resolve($this->getTransport()->getHydrator()->hydrate('Annotation', $annotation)); } return reject(); }); }
/** @test */ public function rejectShouldMakePromiseImmutable() { $adapter = $this->getPromiseTestAdapter(); $mock = $this->createCallableMock(); $mock->expects($this->once())->method('__invoke')->with($this->identicalTo(1)); $adapter->promise()->then(null, function ($value) use($adapter) { $adapter->reject(3); return Promise\reject($value); })->then($this->expectCallableNever(), $mock); $adapter->reject(1); $adapter->reject(2); }
public function refresh() : PromiseInterface { return $this->getTransport()->request('repos/' . $this->repositoryId() . '/caches')->then(function ($json) { foreach ($json['caches'] as $cache) { if ($cache['slug'] != $this->slug()) { continue; } return resolve($this->getTransport()->getHydrator()->hydrate('Cache', $cache)); } return reject(); }); }
/** * @return PromiseInterface */ public function refresh() : PromiseInterface { return $this->getTransport()->request('accounts')->then(function ($json) { foreach ($json['accounts'] as $account) { if ($account['id'] != $this->id()) { continue; } return resolve($this->getTransport()->getHydrator()->hydrate('Account', $account)); } return reject(); }); }
public function fetchDirectory($path, $revision = null, $showAttic = false) { if (substr($path, -1) !== '/') { return Promise\reject(new InvalidArgumentException('Directory path MUST end with trailing slash')); } // TODO: path MUST end with trailing slash // TODO: accessing files will redirect to file with relative location URL (not supported by clue/buzz-react) return $this->fetchXml($this->uri->expand('{+path}{?pathrev,hideattic}', array('path' => $path, 'pathrev' => $revision, 'hideattic' => $showAttic ? '0' : null)))->then(function (SimpleXMLElement $xml) { // TODO: reject if this is a file, instead of directory => contains "Log of" instead of "Index of" // TODO: see is-a-file.html return $xml; })->then(array($this->parser, 'parseDirectoryListing')); }
/** * @covers React\Dns\Query\RetryExecutor * @test */ public function queryShouldForwardNonTimeoutErrors() { $executor = $this->createExecutorMock(); $executor->expects($this->once())->method('query')->with('8.8.8.8', $this->isInstanceOf('React\\Dns\\Query\\Query'))->will($this->returnCallback(function ($domain, $query) { return Promise\reject(new \Exception()); })); $callback = $this->expectCallableNever(); $errorback = $this->createCallableMock(); $errorback->expects($this->once())->method('__invoke')->with($this->isInstanceOf('Exception')); $retryExecutor = new RetryExecutor($executor, 2); $query = new Query('igor.io', Message::TYPE_A, Message::CLASS_IN, 1345656451); $retryExecutor->query('8.8.8.8', $query)->then($callback, $errorback); }
/** * @return PromiseInterface */ public function isActive() : PromiseInterface { return $this->getTransport()->request('hooks')->then(function ($response) { $active = false; foreach ($response['hooks'] as $hook) { if ($hook['id'] == $this->id()) { $active = (bool) $hook['active']; break; } } if ($active) { return resolve($active); } return reject($active); }); }
public function testAwaitAllWithRejectedWillCancelPending() { $cancelled = false; $promise = new Promise\Promise(function () { }, function () use(&$cancelled) { $cancelled = true; }); $all = array(Promise\reject(new Exception('test')), $promise); try { Block\awaitAll($all, $this->loop); $this->fail(); } catch (Exception $expected) { $this->assertEquals('test', $expected->getMessage()); $this->assertTrue($cancelled); } }
public function createClient($address) { if (strpos($address, '://') === false) { $address = 'tcp://' . $address; } $parts = parse_url($address); if (!$parts || !isset($parts['host'])) { return Promise\reject(new InvalidArgumentException('Given argument "' . $address . '" is not a valid URI')); } if (!isset($parts['port'])) { $parts['port'] = 4242; } // default to automatic probing protocol unless scheme is explicitly given $probe = 0; if (isset($parts['scheme'])) { if ($parts['scheme'] === 'legacy') { $probe = Protocol::TYPE_LEGACY; } elseif ($parts['scheme'] !== 'tcp') { return Promise\reject(new InvalidArgumentException('Given URI scheme "' . $parts['scheme'] . '" is invalid')); } } $promise = $this->connector->create($parts['host'], $parts['port']); // protocol probe not already set if ($probe === 0) { $connector = $this->connector; $prober = $this->prober; $promise = $promise->then(function (Stream $stream) use($prober, &$probe, $connector, $parts) { return $prober->probe($stream)->then(function ($ret) use(&$probe, $stream) { // probe returned successfully, create new client for this stream $probe = $ret; return $stream; }, function ($e) use($connector, $parts) { // probing failed if ($e->getCode() === Prober::ERROR_CLOSED) { // legacy servers will terminate connection while probing // let's just open a new connection and assume default probe return $connector->create($parts['host'], $parts['port']); } throw $e; }); }); } return $promise->then(function (Stream $stream) use(&$probe) { return new Client($stream, Protocol::createFromProbe($probe)); }); }
public function testListenerThrowsExceptionWhenRejectedPromiseWithThrowable() { if (!interface_exists('Throwable')) { $this->markTestSkipped('The Throwable interface does not exist.'); } $loop = Factory::create(); $error = new \Error(); $promise = Promise\reject($error); $event = $this->getMockBuilder(GetResponseForControllerResultEvent::class)->disableOriginalConstructor()->getMock(); $event->expects($this->once())->method('getControllerResult')->willReturn($promise); $listener = new PromiseListener($loop); try { $listener->onKernelView($event); $this->fail('->onKernelView() throws exception on rejected promise'); } catch (\Throwable $e) { $this->assertEquals($error, $e); } }
/** * @covers React\Dns\Query\CachedExecutor * @test */ public function callingQueryTwiceShouldUseCachedResult() { $cachedRecords = array(new Record('igor.io', Message::TYPE_A, Message::CLASS_IN)); $executor = $this->createExecutorMock(); $executor->expects($this->once())->method('query')->will($this->callQueryCallbackWithAddress('178.79.169.131')); $cache = $this->getMockBuilder('React\\Dns\\Query\\RecordCache')->disableOriginalConstructor()->getMock(); $cache->expects($this->at(0))->method('lookup')->with($this->isInstanceOf('React\\Dns\\Query\\Query'))->will($this->returnValue(Promise\reject())); $cache->expects($this->at(1))->method('storeResponseMessage')->with($this->isType('integer'), $this->isInstanceOf('React\\Dns\\Model\\Message')); $cache->expects($this->at(2))->method('lookup')->with($this->isInstanceOf('React\\Dns\\Query\\Query'))->will($this->returnValue(Promise\resolve($cachedRecords))); $cachedExecutor = new CachedExecutor($executor, $cache); $query = new Query('igor.io', Message::TYPE_A, Message::CLASS_IN, 1345656451); $cachedExecutor->query('8.8.8.8', $query, function () { }, function () { }); $cachedExecutor->query('8.8.8.8', $query, function () { }, function () { }); }