/** * Return a promise for async requests. * * @param string $method * @param string $url * @param array $body * @param array $query * @param array $headers * * @return \GuzzleHttp\Promise\PromiseInterface */ public function requestAsync($method, $url, $body = [], $query = [], $headers = []) { if (!empty($body)) { $body = encode($body); $headers['Content-Type'] = 'application/json'; } else { $body = null; } $headers = array_merge($this->global_headers, $headers); return $this->client->requestAsync($method, $url, ['query' => $query, 'body' => $body, 'headers' => $headers]); }
/** * @param string $targetUrl target url to import resource into * @param string $file path to file being loaded * @param OutputInterface $output output of the command * @param Document $doc document to load * @param string $host host to import into * @param string $rewriteHost string to replace with value from $host during loading * @param string $rewriteTo string to replace value from $rewriteHost with during loading * @param boolean $sync send requests syncronously * * @return Promise\Promise|null */ protected function importResource($targetUrl, $file, OutputInterface $output, Document $doc, $host, $rewriteHost, $rewriteTo, $sync = false) { $content = str_replace($rewriteHost, $rewriteTo, $doc->getContent()); $successFunc = function (ResponseInterface $response) use($output) { $output->writeln('<comment>Wrote ' . $response->getHeader('Link')[0] . '</comment>'); }; $errFunc = function (RequestException $e) use($output, $file) { $output->writeln('<error>' . str_pad(sprintf('Failed to write <%s> from \'%s\' with message \'%s\'', $e->getRequest()->getUri(), $file, $e->getMessage()), 140, ' ') . '</error>'); if ($output->getVerbosity() >= OutputInterface::VERBOSITY_VERBOSE) { $this->dumper->dump($this->cloner->cloneVar($this->parser->parse($e->getResponse()->getBody(), false, false, true)), function ($line, $depth) use($output) { if ($depth > 0) { $output->writeln('<error>' . str_pad(str_repeat(' ', $depth) . $line, 140, ' ') . '</error>'); } }); } }; if ($sync === false) { $promise = $this->client->requestAsync('PUT', $targetUrl, ['json' => $this->parseContent($content, $file)]); $promise->then($successFunc, $errFunc); } else { $promise = new Promise\Promise(); try { $promise->resolve($successFunc($this->client->request('PUT', $targetUrl, ['json' => $this->parseContent($content, $file)]))); } catch (BadResponseException $e) { $promise->resolve($errFunc($e)); } } return $promise; }
/** * Create and send an HTTP request and return the decoded JSON response * body * * @throws EWSClientError * * @param string $method * HTTP method e.g. GET, POST, DELETE * @param array $uris * URI strings * @param array $options * Request options to apply * @return mixed * JSON decoded body from EWS */ public function requestJsons($method, $uris, array $options = []) { // Add the OAuth access token to the request headers $options = array_merge($options, ['headers' => ['Authorization' => 'Bearer ' . $this->accessToken]]); /** @var Promise\PromiseInterface[] $promises */ $promises = []; $transactionIds = []; $counter = 0; foreach ($uris as $uri) { $transactionIds[] = Uuid::uuid4()->toString(); $this->logRequest($transactionIds[$counter], $method, $uri, $options); $promises[] = $this->http->requestAsync($method, $uri, $options); } try { $responses = Promise\unwrap($promises); $results = []; $counter = 0; foreach ($responses as $response) { $this->logResponse($transactionIds[$counter], $method, $uris[$counter], $response); $results[] = $this->handleResponse($response); $counter++; } } catch (ClientException $e) { throw new EWSClientError($e->getCode() . ' error', 0, null, []); } return $results; }
public function requestAsync($url, $method = 'GET', $data = []) { $stack = HandlerStack::create(); $stack->push(ApiMiddleware::auth()); $client = new Client(['handler' => $stack]); $promise = $client->requestAsync($method, $url, ['headers' => ['Authorization' => 'Bearer ' . $this->token], 'json' => $data, 'content-type' => 'application/json']); return $promise; }
/** * @param $method * @param $args * @return \GuzzleHttp\Promise\PromiseInterface|mixed|\Psr\Http\Message\ResponseInterface */ public function __call($method, $args) { if (count($args) < 1) { throw new \InvalidArgumentException('Magic request methods require a URI and optional options array'); } $uri = $args[0]; $opts = isset($args[1]) ? $args[1] : []; return substr($method, -5) === 'Async' ? $this->client->requestAsync(substr($method, 0, -5), $uri, $opts) : $this->client->request($method, $uri, $opts); }
/** * Do a HTTP request * * @param string $method * @param string $uri * @param array $options * @return \GuzzleHttp\Promise\PromiseInterface|Response */ public function requestAsync($method, $uri = null, array $options = []) { if (isset($options['data'])) { if (in_array($method, ['GET', 'HEAD', 'OPTIONS'])) { $options['query'] = $options['data']; unset($options['data']); } else { $this->applyPostData($options); } } return parent::requestAsync($method, $uri, $options); }
/** * Pass undefined requests to client * * @param string $method * @param arary $args * * @return \GuzzleHttp\Psr7\Response */ public function __call($method, $args) { $paths = isset($args[0]) ? $args[0] : false; $params = isset($args[1]) ? $args[1] : []; if (substr($method, -4) === 'Many') { $promises = []; foreach ($paths as $path) { $promises[$path] = $this->client->requestAsync(substr($method, 0, -4), '/' . $path, $params); } return Promise\unwrap($promises); } return $this->client->request($method, $paths ? '/' . $paths : null, $params); }
public static function logout(UserAuthTicket $authTicket) { try { $authentication = AppAuthenticator::getInstance(); //var_dump($authTicket); $resourceUrl = static::getLogoutUrl($authTicket); $client = new Client(['base_uri' => MozuConfig::$baseAppAuthUrl, 'verify' => false]); $headers = ["content-type" => "application/json", Headers::X_VOL_APP_CLAIMS => $authentication->getAppClaim()]; var_dump($headers); $promise = $client->requestAsync("DELETE", $resourceUrl, ['headers' => $headers, 'exceptions' => true]); $promise->wait(); } catch (\Exception $e) { HttpHelper::checkError($e); } }
private function refreshAuthTicket() { try { $requestData = new AuthTicketRequest(); $requestData->refreshToken = $this->authTicket->refreshToken; $client = new Client(['base_uri' => MozuConfig::$baseAppAuthUrl, 'verify' => false]); $headers = ["content-type" => "application/json"]; $body = json_encode($requestData); $promise = $client->requestAsync("PUT", AuthTicketUrl::RefreshAppAuthTicketUrl(null)->getUrl(), ['headers' => $headers, 'body' => $body, 'exceptions' => true]); $response = $promise->wait(); $jsonResp = $response->getBody(true); $this->authTicket = json_decode($jsonResp); $this->setRefreshInterval(true); } catch (\Exception $e) { HttpHelper::checkError($e); } }
public static function authenticate(CustomerUserAuthInfo $customerAuthInfo, $tenantId, $siteId) { try { $authentication = AppAuthenticator::getInstance(); $resourceUrl = CustomerAuthTicketUrl::createUserAuthTicketUrl(null); $client = new Client(['base_uri' => static::getAuthUrl($tenantId), 'verify' => false]); $headers = ["content-type" => "application/json", Headers::X_VOL_APP_CLAIMS => $authentication->getAppClaim(), Headers::X_VOL_SITE => $siteId]; $body = json_encode($customerAuthInfo); $promise = $client->requestAsync($resourceUrl->getVerb(), $resourceUrl->getUrl(), ['headers' => $headers, 'body' => $body, 'exceptions' => true]); $response = $promise->wait(); $jsonResp = $response->getBody(true); $authResponse = json_decode($jsonResp); $authProfile = static::setUserAuth($authResponse, $tenantId, $siteId); return $authProfile; } catch (\Exception $e) { HttpHelper::checkError($e); } }
/** * Create and send an HTTP request and return the decoded JSON response * body * * @throws EWSClientError * * @param string $method * HTTP method e.g. GET, POST, DELETE * @param array $uris * URI strings * @param array $options * Request options to apply * @return mixed * JSON decoded body from EWS */ public function requestJsons($method, $uris, array $options = []) { // Add the OAuth access token to the request headers $options = array_merge($options, ['headers' => ['Authorization' => 'Bearer ' . $this->accessToken]]); $promises = []; foreach ($uris as $uri) { $promises[] = $this->http->requestAsync($method, $uri, $options); } try { $responses = Promise\unwrap($promises); $results = []; foreach ($responses as $response) { $results[] = $this->handleResponse($response); } } catch (ClientException $e) { throw new EWSClientError($e->getCode() . ' error', 0, null, []); } return $results; }
/** * @param UriInterface $url * @param Session $session * * @return Promise * * @resolves bool True if the module was just disconnected, false if it was already disconnected. * * @rejects RequestException * @rejects OxygenPageNotFoundException */ public function disconnectOxygenAsync(UriInterface $url, Session $session) { return $this->client->getAsync($url->withQuery(\GuzzleHttp\Psr7\build_query(['q' => 'admin/config/oxygen/disconnect'])), [RequestOptions::COOKIES => $session->getCookieJar(), RequestOptions::AUTH => $session->getAuthData()])->then(function (ResponseInterface $response) use($url, $session) { $crawler = new Crawler((string) $response->getBody(), (string) $url); try { $form = $crawler->filter('form#oxygen-admin-disconnect')->form(); if ($form->get('oxygen_connected')->getValue() === 'yes') { return $this->client->requestAsync($form->getMethod(), $form->getUri(), [RequestOptions::COOKIES => $session->getCookieJar(), RequestOptions::AUTH => $session->getAuthData(), RequestOptions::HEADERS => ['referer' => $form->getUri()], RequestOptions::FORM_PARAMS => $form->getPhpValues()]); } return false; } catch (\Exception $e) { throw new OxygenPageNotFoundException(); } })->then(function ($result) { if (!$result instanceof ResponseInterface) { // Module was already disconnected. return false; } // Module was successfully disconnected. return true; }); }
/** * @inheritdoc */ public function multiRequest(array $urls) { $client = new Client(); $promises = array(); foreach ($urls as $urlName => $urlData) { if (is_string($urlData)) { $urlData = array($urlData, array()); } $urlOptions = new Options($urlData[1]); $method = $urlOptions->get('method', 'GET', 'up'); $args = $urlOptions->get('args'); $url = 'GET' === $method ? Url::addArg((array) $args, $urlData[0]) : $urlData[0]; $promises[$urlName] = $client->requestAsync($method, $url, $this->_getClientOptions($urlOptions, $method, $args)); } $httpResults = Promise\unwrap($promises); /** @var string $resName */ /** @var Response $httpResult */ $result = array(); foreach ($httpResults as $resName => $httpResult) { $result[$resName] = array($httpResult->getStatusCode(), $httpResult->getHeaders(), $httpResult->getBody()->getContents()); } return $result; }
public function requestAsync($method, $endpoint, array $data = array()) { $promise = $this->client->requestAsync($method, $this->api_prefix . $endpoint, $this->getRequestOptions($method, $data))->then(function (ResponseInterface $res) { return $this->getBody($res); }, function (RequestException $e) { // See if we can simplify the exception. if (!$e->hasResponse()) { throw new StockfighterRequestException('', -1, 'No response from server.'); } $this->handleResponseErrors($e->getResponse()); // Otherwise, throw a general error. throw new StockfighterRequestException('', -1, 'Unknown error: ' . $e->getMessage()); })->then($this->global_fulfilled, $this->global_rejected); // Add a timer to the loop to monitor this request. $timer = $this->stockfighter->loop->addPeriodicTimer(0, \Closure::bind(function () use(&$timer) { $this->tick(); if (empty($this->handles) && Promise\queue()->isEmpty()) { $timer->cancel(); } }, $this->handler, $this->handler)); // Return the promise. return $promise; }
/** * @inheritDoc */ public function requestAsync($method, $uri, array $options = []) { return $this->client->requestAsync($method, $uri, $options); }
<?php namespace Action; require "BaseAction.php"; use GuzzleHttp\Client; use Psr\Http\Message\ResponseInterface; use GuzzleHttp\Exception\RequestException; // $client = new Client(['timeout' => 10]); $client = new Client(['base_uri' => 'http://127.0.0.1/test/index.php', 'timeout' => 10]); // $response = $client->request('GET'); // var_dump($response->getBody()->getContents()); // exit(__FILE__ . __LINE__); $promise = $client->requestAsync('GET', 'http://httpbin.org/get'); $promise->then(function (ResponseInterface $res) { var_dump($res->getBody()->getContents()); echo $res->getStatusCode() . "\n"; }, function (RequestException $e) { echo $e->getMessage() . "\n"; echo $e->getRequest()->getMethod(); }); echo "do something"; $promise->wait(); echo 22;