/** * This method adds the current parameter to the specified REST API request. * * @param \GuzzleHttp\Psr7\Request $request * @return Request */ public function apply(Request $request) { $queryString = $request->getUri()->getQuery(); $queryParts = \GuzzleHttp\Psr7\parse_query($queryString); $queryParts[$this->name] = $this->value; $queryString = \GuzzleHttp\Psr7\build_query($queryParts); return $request->withUri($request->getUri()->withQuery($queryString)); }
/** * Returns the balance of the supplied account. * * @link https://getmondo.co.uk/docs/#balance * * @param string $id * * @return Balance */ public function get($id) { $query = \GuzzleHttp\Psr7\build_query(['account_id' => $id]); $request = new Request('get', "/balance?{$query}"); $response = $this->sendRequest($request); return new Balance($response); }
public function getFit($rawOptions) { $options = array_only($rawOptions, ['width', 'height']); if (empty($options)) { return $this->getFull(); } $fitName = $this->hash . '-' . urlencode(\GuzzleHttp\Psr7\build_query($options)) . '.' . $this->extension; $fitPath = storage_path("images/fit/{$fitName}"); if (\File::exists($fitPath)) { return \File::get($fitPath); } $img = ImageLib::make($this->getPath()); $newWidth = array_get($options, 'width', null); $newHeight = array_get($options, 'height', null); if ($newWidth) { if ($newHeight) { // both width and height $img->fit($newWidth, $newHeight); } else { // Only Width $img->widen($newWidth); } } else { if ($newHeight) { // only height $img->heighten($newHeight); } } $img->save($fitPath); return \File::get($fitPath); }
/** * Converts an array of parameters into a multipart stream which can be used in an api request. * * @param array $parameters * @param $name * * @return MultipartStream */ protected function parseParameters(array $parameters, $name) { $parsed = []; foreach ($parameters as $key => $value) { $parsed["{$name}[{$key}]"] = $value; } return \GuzzleHttp\Psr7\build_query($parsed, false); }
public function testSetterMethodsArePipedToWrappedRequestSetQuery() { $fixtureQuery = ['size' => 5]; $orgRequest = $this->getMockBuilder('Psr\\Http\\Message\\RequestInterface')->disableOriginalConstructor()->getMock(); $uri = $this->getMockBuilder('Psr\\Http\\Message\\UriInterface')->disableOriginalConstructor()->getMock(); $uri->expects($this->once())->method('withQuery')->with($this->equalTo(\GuzzleHttp\Psr7\build_query($fixtureQuery)))->willReturn($uri); $orgRequest->expects($this->once())->method('getUri')->willReturn($uri); $orgRequest->expects($this->once())->method('withUri')->with($uri); $guzzleRequest = new GuzzleTransportRequest($orgRequest); $guzzleRequest->setQueryParams($fixtureQuery); }
/** * @param Site $site * @param string $userId ID of the user that initiates the session. It is used to track individual sessions so they can be destroyed * on demand. This value is signed, so it cannot be intercepted. * @param string|null $userName User to log in as. Pass null to use the user with ID 1, which should always exist and have full privileges * (hardcoded in Drupal). This value is signed, so it cannot be intercepted. * * @return UriInterface */ public function generateUrl(Site $site, $userId, $userName = null) { $requestId = bin2hex(random_bytes(16)); $requestExpiresAt = time() + 86400; $query = ['oxygenRequestId' => $requestId, 'requestExpiresAt' => $requestExpiresAt, 'actionName' => 'site.login', 'signature' => \Undine\Functions\openssl_sign_data($site->getPrivateKey(), sprintf('%s|%d|%s|%s', $requestId, $requestExpiresAt, $userId, (string) $userName)), 'userName' => $userName, 'userId' => $userId]; $url = $site->getUrl(); if ($site->hasHttpCredentials()) { $url = $url->withUserInfo($site->getHttpCredentials()->getUsername(), $site->getHttpCredentials()->getPassword()); } return $url->withQuery(\GuzzleHttp\Psr7\build_query($query)); }
public function testUseAllParams() { $keyword = 'keyword_test'; $country = 'es'; $language = 'es'; $excludeKeywords = ['exclude', 'exclude_1']; $serviceUrl = 'http://some.api.url.com/test'; $request = new Request($keyword, $serviceUrl); $request->complete(true)->country('es')->type()->excludeKeywords($excludeKeywords)->language('es')->metrics(true); $params = ['keyword' => $keyword, 'complete' => 'true', 'country' => $country, 'type' => 'suggestions', 'exclude' => join('|', $excludeKeywords), 'language' => $language, 'metrics' => 'true']; $this->assertEquals($serviceUrl . '?' . \GuzzleHttp\Psr7\build_query($params), (string) $request->getUri()); }
/** * Adds annotation metadata to a transaction. * * @link https://getmondo.co.uk/docs/#annotate-transaction * * @param string $transactionId * @param array $metadata * @param bool $expandMerchant * * @return Transaction */ public function annotate($transactionId, array $metadata, $expandMerchant = true) { $query = []; if ($expandMerchant) { $query += ['expand[]' => 'merchant']; } $query = \GuzzleHttp\Psr7\build_query($query); $request = new Request('patch', "/transactions/{$transactionId}?{$query}", ['Content-Type' => 'application/x-www-form-urlencoded'], $this->parseParameters($metadata, 'metadata')); $response = $this->sendRequest($request); $response = json_decode($response->getBody()->getContents(), true); return new Transaction($response['transaction']); }
/** * @vcr Authentication/testInitiateAuthorizationInvalid.json * @link https://familysearch.org/developers/docs/api/authentication/Initiate_Authorization_(Invalid_Parameter)_usecase */ public function testInitiateAuthorizationInvalid() { $factory = new StateFactory(); $collectionState = $factory->newCollectionState(); $link = $collectionState->getLink(Rel::OAUTH2_AUTHORIZE); $request = new Request('GET', $link->getHref(), ['Accept' => Gedcomx::HTML_TYPE]); $request = $request->withUri($request->getUri()->withQuery(\GuzzleHttp\Psr7\build_query(['response_type' => 'code', 'client_id' => $this->clientId, 'redirect_uri' => 'https://hrpufnstuf.org/witchiepoo']))); $response = $collectionState->getClient()->send($request); $doc = $response->getBody(); $hasInput = strpos($doc, 'Oauth2 error') !== false ? true : false; $this->assertTrue($hasInput); }
/** * @param $endpoint * @param ServerRequestInterface $request * * @return ResponseInterface */ public function proxy($endpoint, ServerRequestInterface $request) { /** @var ClientInterface $client */ $client = $this->container->get('bangpound_guzzle_proxy.client.' . $endpoint); $rel = $request->getAttribute('path'); if ($request->getQueryParams()) { $rel .= '?' . \GuzzleHttp\Psr7\build_query($request->getQueryParams()); } $rel = new Uri($rel); $uri = $client->getConfig('base_url'); $uri = new Uri($uri); $uri = Uri::resolve($uri, $rel); $request = \GuzzleHttp\Psr7\modify_request($request, array('uri' => $uri)); $response = $client->send($request); if ($response->hasHeader('Transfer-Encoding')) { $response = $response->withoutHeader('Transfer-Encoding'); } return $response; }
/** * @param array $params * * @return void * @author Mario Mueller */ public function setQueryParams(array $params) { $uri = $this->guzzleRequest->getUri()->withQuery(\GuzzleHttp\Psr7\build_query($params)); $this->guzzleRequest = $this->guzzleRequest->withUri($uri); }
/** * @return \Psr\Http\Message\UriInterface */ public function getUri() { $uri = new Uri($this->serviceUri); return $uri->withQuery(\GuzzleHttp\Psr7\build_query($this->params)); }
/** * This is the main method of this wrapper. It will * sign a given query and return its result. * * @param string $method HTTP method of request (GET,POST,PUT,DELETE) * @param string $path relative url of API request * @param \stdClass|array|null $content body of the request * @param bool $is_authenticated if the request use authentication * * @return array * @throws \GuzzleHttp\Exception\ClientException if http request is an error */ private function rawCall($method, $path, $content = null, $is_authenticated = true) { $url = $this->endpoint . $path; $request = new Request($method, $url); if (isset($content) && $method == 'GET') { $queryString = $request->getUri()->getQuery(); $query = false !== strpos($queryString, '&') ? explode('&', $queryString) : []; $query = array_merge($query, (array) $content); $query = \GuzzleHttp\Psr7\build_query($query); $request = $request->withUri($request->getUri()->withQuery($query)); $body = ""; } elseif (isset($content)) { $body = json_encode($content); $request->getBody()->write($body); } else { $body = ""; } $headers = ['Content-Type' => 'application/json; charset=utf-8', 'X-Ovh-Application' => $this->application_key]; if ($is_authenticated) { if (!isset($this->time_delta)) { $this->calculateTimeDelta(); } $now = time() + $this->time_delta; $headers['X-Ovh-Timestamp'] = $now; if (isset($this->consumer_key)) { $toSign = $this->application_secret . '+' . $this->consumer_key . '+' . $method . '+' . $url . '+' . $body . '+' . $now; $signature = '$1$' . sha1($toSign); $headers['X-Ovh-Consumer'] = $this->consumer_key; $headers['X-Ovh-Signature'] = $signature; } } /** @var Response $response */ $response = $this->http_client->send($request, ['headers' => $headers]); return json_decode($response->getBody(), true); }
public function subscribe(ObserverInterface $observer, $scheduler = null) { $socket = new \React\Socket\Server(\EventLoop\getLoop()); $negotiator = new Negotiator(new Validator()); if (!empty($this->subProtocols)) { $negotiator->setSupportedSubProtocols($this->subProtocols); } $http = new \React\Http\Server($socket); $http->on('request', function (Request $request, Response $response) use($negotiator, $observer, &$outStream) { $uri = new Uri($request->getPath()); if (count($request->getQuery()) > 0) { $uri = $uri->withQuery(\GuzzleHttp\Psr7\build_query($request->getQuery())); } $psrRequest = new \GuzzleHttp\Psr7\Request($request->getMethod(), $uri, $request->getHeaders()); // cram the remote address into the header in out own X- header so // the user will have access to it $psrRequest = $psrRequest->withAddedHeader("X-RxWebsocket-Remote-Address", $request->remoteAddress); $negotiatorResponse = $negotiator->handshake($psrRequest); $response->writeHead($negotiatorResponse->getStatusCode(), array_merge($negotiatorResponse->getHeaders(), ["Content-Length" => "0"])); if ($negotiatorResponse->getStatusCode() !== 101) { $response->end(); return; } $subProtocol = ""; if (count($negotiatorResponse->getHeader('Sec-WebSocket-Protocol')) > 0) { $subProtocol = $negotiatorResponse->getHeader('Sec-WebSocket-Protocol')[0]; } $connection = new MessageSubject(new AnonymousObservable(function (ObserverInterface $observer) use($request) { $request->on('data', function ($data) use($observer) { $observer->onNext($data); }); $request->on('error', function ($error) use($observer) { $observer->onError($error); }); $request->on('close', function () use($observer) { $observer->onCompleted(); }); $request->on('end', function () use($observer) { $observer->onCompleted(); }); return new CallbackDisposable(function () use($request) { $request->close(); }); }), new CallbackObserver(function ($x) use($response) { $response->write($x); }, function ($error) use($response) { $response->close(); }, function () use($response) { $response->end(); }), false, $this->useMessageObject, $subProtocol, $psrRequest, $negotiatorResponse); $observer->onNext($connection); }); $socket->listen($this->port, $this->bindAddress); // $http->on('end', function () {}); // $http->on('data', function () {}); // $http->on('pause', function () {}); // $http->on('resume', function () {}); $this->started = true; return new CallbackDisposable(function () use($socket) { $socket->shutdown(); }); }
protected function getEnumFacet($facetName, $facetConfig, UriInterface $searchUri, $queryParams) { $attributeName = $facetConfig['attribute']; $cache = $this->get('app.cache'); $cacheKey = $facetName . '-facet-' . $this->locale; $typeData = $this->get('app.repository.productType')->getTypes(); if (!$cache->has($cacheKey)) { $facetValues = []; /** * @var ProductTypeCollection $typeData */ foreach ($typeData as $productType) { /** * @var AttributeDefinition $attribute */ $attribute = $productType->getAttributes()->getByName($attributeName); if (is_null($attribute)) { continue; } /** * @var LocalizedEnumType $attributeType */ $attributeType = $attribute->getType(); $values = $attributeType->getValues(); foreach ($values as $value) { if (isset($facetValues[$value->getKey()])) { continue; } $facetEntry = new ViewData(); $facetEntry->value = $value->getKey(); $facetEntry->label = (string) $value->getLabel(); $facetValues[$value->getKey()] = $facetEntry; } } $cache->store($cacheKey, serialize($facetValues)); } else { $facetValues = unserialize($cache->fetch($cacheKey)); } $facetData = new ViewData(); $facetData->displayList = $facetConfig['display'] == 'list'; $facetData->selectFacet = true; $facetData->facet = new ViewData(); if ($facetConfig['multi'] == true) { $facetData->facet->multiSelect = $facetConfig['multi']; } $facetData->facet->available = true; $facetData->facet->label = $this->trans('filters.' . $facetName, [], 'catalog'); $facetData->facet->key = $facetName; $limitedOptions = new ViewDataCollection(); $selectedValues = array_diff_key($queryParams, [$facetName => true]); $facetData->facet->clearUri = $searchUri->withQuery(\GuzzleHttp\Psr7\build_query($selectedValues)); foreach ($this->facets->getByName($facetName)->getTerms() as $term) { $key = $term->getTerm(); $facetEntry = $facetValues[$term->getTerm()]; $facetSelection = isset($queryParams[$facetName]) ? $queryParams[$facetName] : []; if (!is_array($facetSelection)) { $facetSelection = [$facetSelection]; } if (in_array($key, $facetSelection)) { $facetEntry->selected = true; $uriValues = array_merge($selectedValues, [$facetName => array_diff($facetSelection, [$key])]); } else { $uriValues = array_merge($selectedValues, [$facetName => array_merge($facetSelection, [$key])]); } $uri = $searchUri->withQuery(\GuzzleHttp\Psr7\build_query($uriValues)); $facetEntry->uri = $uri; $facetEntry->count = $term->getCount(); $limitedOptions->add($facetEntry); } $facetData->facet->limitedOptions = $limitedOptions; return $facetData; }
/** * @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; }); }
$imageFormats = ['list' => ['w' => 800, 'h' => 400, 'fit' => 'fill'], 'detail' => ['w' => 720, 'h' => 405, 'fit' => 'fill', 'f' => 'faces']]; $methodName = 'get' . ucfirst($fieldName); $assets = $entry->{$methodName}(); if (count($assets) === 0) { return []; } $images = []; /** @var \Contentful\Delivery\DynamicEntry $asset */ foreach ($assets as $asset) { try { $client = new \GuzzleHttp\Client(); $fileName = $asset->getImage()->getFile()->getFileName(); $fileExtension = strtolower(pathinfo($fileName, PATHINFO_EXTENSION)); $formats = []; foreach ($imageFormats as $formatName => $imageFormat) { $url = $asset->getImage()->getFile()->getUrl() . '?' . \GuzzleHttp\Psr7\build_query($imageFormat); $persistedFileName = md5($url) . '.' . $fileExtension; $persistedFilePath = $imageFolder . DIRECTORY_SEPARATOR . $persistedFileName; if (!file_exists($persistedFilePath)) { $client->request('GET', $url, ['sink' => $persistedFilePath]); } $formats[$formatName] = $persistedFileName; } $images[] = $formats; } catch (\Exception $exception) { } } return $images; }; $youtube = function ($fieldName, \Contentful\Delivery\DynamicEntry $entry) use($fieldMapping, $locale) { $methodName = 'get' . ucfirst($fieldName);
private function invokeSignedRequest($httpMethod, $endpointURL, $reqPath, $headers = array(), $params = array(), $jsonEntity = null) { if (empty($this->accessKey)) { trigger_error("Blank access key: " . $httpMethod . " " . $reqPath, E_USER_WARNING); return null; } $doSign = $this->tokenKey == null; if (empty($this->secretKey) && empty($this->tokenKey)) { if ($headers == null) { $headers = array(); } $headers["Authorization"] = "Anonymous " . $this->accessKey; $doSign = false; } $headers = $headers == null ? array() : $headers; $query = array(); if ($params != null) { foreach ($params as $key => $value) { if (is_array($value) && !empty($value)) { // no spec on this case, so choose first param in array $query[$key] = $value[0]; } else { $query[$key] = $value; } } } if ($this->tokenKey != null) { // make sure you don't create an infinite loop! if (!($httpMethod == "GET" && $reqPath == self::JWT_PATH)) { $this->refreshToken(); } $headers["Authorization"] = "Bearer " . $this->tokenKey; } // only sign some of the query parameters $queryString = empty($query) ? "" : "?" . \GuzzleHttp\Psr7\build_query($query); $req = new Request($httpMethod, $endpointURL . $reqPath . $queryString, $headers, $jsonEntity); if ($doSign) { $sig = new SignatureV4("para", "us-east-1"); $req = $sig->signRequest($req, new Credentials($this->accessKey, $this->secretKey)); } // send all query parameters to the server $queryString = $params == null ? "" : \GuzzleHttp\Psr7\build_query($params); try { return $this->apiClient->send($req, array(RequestOptions::QUERY => $queryString)); } catch (\Exception $ex) { error_log($ex->getMessage(), 0); } return null; }
/** * Call any path, GET method * Ex: $api->get('me'). * * @param string $path the Api path * @param array $parameters GET parameters * @param array $requestOptions reconfigure the request * * @return array */ public function get($path, array $parameters = array(), $requestOptions = array()) { $request = new Request('GET', $this->options['path'] . '/' . $path . '?' . \GuzzleHttp\Psr7\build_query($parameters), array_merge($requestOptions, ['Authorization' => 'Bearer ' . $this->options['token']])); return $this->handleRequest($request, $requestOptions); }
/** * @param string $path * @param array $parameters * @return static */ public static function withPath($path, array $parameters = []) { $queryString = \GuzzleHttp\Psr7\build_query($parameters); return new static(sprintf('Resource not found at path: %s [parameters: %s]', $path, $queryString)); }
private function onBefore(RequestInterface $request) { $oauthparams = $this->getOauthParams($this->generateNonce($request), $this->config); $oauthparams['oauth_signature'] = $this->getSignature($request, $oauthparams); uksort($oauthparams, 'strcmp'); switch ($this->config['request_method']) { case self::REQUEST_METHOD_HEADER: list($header, $value) = $this->buildAuthorizationHeader($oauthparams); $request = $request->withHeader($header, $value); break; case self::REQUEST_METHOD_QUERY: $queryparams = \GuzzleHttp\Psr7\parse_query($request->getUri()->getQuery()); $preparedParams = \GuzzleHttp\Psr7\build_query($oauthparams + $queryparams); $request = $request->withUri($request->getUri()->withQuery($preparedParams)); break; default: throw new \InvalidArgumentException(sprintf('Invalid consumer method "%s"', $this->config['request_method'])); } return $request; }
protected function getHeaderViewData($title, Request $request = null) { $session = $this->get('session'); $header = new Header($title); $header->stores = new Url($this->trans('header.stores'), ''); $header->help = new Url($this->trans('header.help'), ''); $header->callUs = new Url($this->trans('header.callUs', ['phone' => $this->config['sunrise.header.callUs']]), ''); $header->location = new ViewData(); $languages = new ViewDataCollection(); $routeParams = $request->get('_route_params'); $queryParams = \GuzzleHttp\Psr7\parse_query($request->getQueryString()); foreach ($this->config['languages'] as $language) { $languageEntry = new ViewData(); if ($language == \Locale::getPrimaryLanguage($this->locale)) { $languageEntry->selected = true; } $languageEntry->label = $this->trans('header.languages.' . $language); $routeParams['_locale'] = $language; $languageUri = $this->generateUrl($request->get('_route'), $routeParams); $uri = new Uri($languageUri); $languageEntry->value = (string) $uri->withQuery(\GuzzleHttp\Psr7\build_query($queryParams)); $languages->add($languageEntry); } $header->location->language = $languages; // $countries = new ViewDataCollection(); // foreach ($this->config['countries'] as $country) { // $countryEntry = new ViewData(); // $countryEntry->label = $this->trans('header.countries.' . $country); // $countryEntry->value = $country; // $countries->add($countryEntry); // } // // $header->location->country = $countries; $header->user = new ViewData(); $header->user->isLoggedIn = false; $header->user->signIn = new Url('Login', ''); $header->miniCart = new ViewData(); $header->miniCart->totalItems = $session->get('cartNumItems', 0); $header->navMenu = $this->getNavMenu(); return $header; }