withQueryValue() public static method

Any existing query string values that exactly match the provided key are removed and replaced with the given key value pair. A value of null will set the query string key without a value, e.g. "key" instead of "key=value".
public static withQueryValue ( Psr\Http\Message\UriInterface $uri, string $key, string | null $value ) : Psr\Http\Message\UriInterface
$uri Psr\Http\Message\UriInterface URI to use as a base.
$key string Key to set.
$value string | null Value to set
return Psr\Http\Message\UriInterface
 /**
  * @param RequestInterface $request
  * @return RequestInterface
  */
 public function __invoke(RequestInterface $request)
 {
     foreach ($this->params as $param => $value) {
         $request = $request->withUri(Uri::withQueryValue($request->getUri(), $param, $value));
     }
     return $request;
 }
 /**
  * @param RequestInterface $request
  *
  * @return RequestInterface
  */
 private function appendQueryParams(RequestInterface $request)
 {
     $queryParams = $this->auth->getQueryParameters();
     foreach ($queryParams as $key => $value) {
         $uri = Uri::withQueryValue($request->getUri(), $key, $value);
         $request = $request->withUri($uri);
     }
     return $request;
 }
 public static function get(array $options, $key)
 {
     $stack = HandlerStack::create();
     $stack->unshift(Middleware::mapRequest(function (RequestInterface $request) use($key) {
         return $request->withUri(Uri::withQueryValue($request->getUri(), 'key', $key));
     }));
     $options['handler'] = $stack;
     return new Client($options);
 }
Ejemplo n.º 4
0
 /**
  * @param RequestInterface $request
  *
  * @return ResponseInterface
  *
  * @throws ApiException | SearchLimitException
  */
 public function research(RequestInterface $request)
 {
     try {
         $response = $this->httpClient->request('GET', Uri::withQueryValue($request->getUri(), 'apikey', $this->apiKey));
         return new Response($response);
     } catch (\GuzzleHttp\Exception\ClientException $ex) {
         throw ExceptionFactory::createThrowable($ex);
     }
 }
Ejemplo n.º 5
0
 /**
  * {@inheritDoc}
  */
 public function __invoke(RequestInterface $request, array $options)
 {
     $next = $this->nextHandler;
     if (!$this->config->has('access_token') || $this->config->get('access_token') === null) {
         return $next($request, $options);
     }
     $uri = Uri::withQueryValue($request->getUri(), 'access_token', $this->config->get('access_token')->getToken());
     return parent::__invoke($request->withUri($uri)->withHeader('Content-Type', 'application/json'), $options);
 }
Ejemplo n.º 6
0
 /**
  * @param $url
  * @param array $params
  *
  * @return \Psr\Http\Message\UriInterface
  */
 private function makeUri($url, $params = array())
 {
     $uri = \GuzzleHttp\uri_template($this->endpoint, array_merge($this->defaults, $params));
     $uri = new Psr7\Uri($uri);
     // All arguments must be urlencoded (as per RFC 1738).
     $query = Psr7\build_query($params, PHP_QUERY_RFC1738);
     $uri = $uri->withQuery($query);
     return Psr7\Uri::withQueryValue($uri, 'url', $url);
 }
 /**
  * Inject credentials information into the query parameters
  *
  * @param RequestInterface $request
  * @param array            $options
  *
  * @return GuzzleResponseInterface
  */
 public function __invoke(RequestInterface $request, array $options)
 {
     if ($request->getUri()->getScheme() == 'https' && $options['auth'] == static::AUTH_NAME) {
         $uri = Uri::withQueryValue($request->getUri(), 'client_id', $this->userKey ?: $this->apiKey);
         $uri = Uri::withQueryValue($uri, 'client_secret', $this->secret);
         $request = $request->withUri($uri);
     }
     $fn = $this->nextHandler;
     return $fn($request, $options);
 }
Ejemplo n.º 8
0
 /**
  * {@inheritDoc}
  */
 public function __invoke(RequestInterface $request, array $options)
 {
     $next = $this->nextHandler;
     if (!$this->config->get('secure_requests')) {
         return $next($request, $options);
     }
     $uri = $request->getUri();
     $sig = $this->generateSig($this->getPath($uri), $this->getQueryParams($uri), $this->config->get('client_secret'));
     $uri = Uri::withQueryValue($uri, 'sig', $sig);
     return parent::__invoke($request->withUri($uri), $options);
 }
 /**
  * @test
  */
 public function invoke_QueryParameters_Success()
 {
     $this->auth->expects($this->once())->method('getHeaders')->willReturn([]);
     $this->auth->expects($this->once())->method('getQueryParameters')->willReturn(['jwt' => 'YYYY', 'otherParam' => 'YYYY']);
     $this->request->expects($this->exactly(3))->method('getUri')->willReturn($this->uri);
     $this->request->expects($this->exactly(2))->method('withUri')->withConsecutive(Uri::withQueryValue($this->uri, 'jwt', 'YYYY'), Uri::withQueryValue($this->uri, 'otherParam', 'YYYY'))->willReturnSelf();
     $middleware = new ConnectMiddleware($this->auth, $this->appContext);
     $callable = $middleware(function (RequestInterface $actualRequest, array $options) {
         $this->assertEquals($this->request, $actualRequest);
         $this->assertEquals(['Hello World'], $options);
     });
     $callable($this->request, ['Hello World']);
 }
Ejemplo n.º 10
0
 /**
  * @return Client
  */
 protected function connect()
 {
     $base_uri = $this->config->get('base_uri');
     if ($this->config->has('transport') && $this->config->has('host') && $this->config->has('port')) {
         $base_uri = sprintf('%s://%s:%s', $this->config->get('transport'), $this->config->get('host'), $this->config->get('port'));
     }
     $client_options = ['base_uri' => $base_uri];
     if ($this->config->get('debug', false)) {
         $client_options['debug'] = true;
     }
     if ($this->config->has('auth')) {
         $auth = (array) $this->config->get('auth');
         if (!isset($auth['username'])) {
             throw new RuntimeError('Missing required "username" setting within given auth config.');
         }
         if (!isset($auth['password'])) {
             throw new RuntimeError('Missing required "password" setting within given auth config.');
         }
         $client_options['auth'] = [$auth['username'], $auth['password'], isset($auth['type']) ? $auth['type'] : 'basic'];
     }
     if ($this->config->has('default_headers')) {
         $client_options['headers'] = (array) $this->config->get('default_headers');
     }
     if ($this->config->has('default_options')) {
         $client_options = array_merge($client_options, (array) $this->config->get('default_options')->toArray());
     }
     if ($this->config->has('default_query')) {
         $handler = HandlerStack::create();
         $handler->push(Middleware::mapRequest(function (RequestInterface $request) {
             $uri = $request->getUri();
             foreach ((array) $this->config->get('default_query')->toArray() as $param => $value) {
                 $uri = Uri::withQueryValue($uri, $param, $value);
             }
             return $request->withUri($uri);
         }));
         $client_options['handler'] = $handler;
     }
     return new Client($client_options);
 }
Ejemplo n.º 11
0
 /**
  * Set request access_token query.
  */
 protected function attachAccessToken()
 {
     if (!$this->accessToken) {
         return;
     }
     // log
     $this->getHttp()->addMiddleware(function (callable $handler) {
         return function (RequestInterface $request, array $options) use($handler) {
             $field = $this->accessToken->getQueryName();
             $token = $this->accessToken->getToken();
             $request = $request->withUri(Uri::withQueryValue($request->getUri(), $field, $token));
             Log::debug("Request Token: {$token}");
             Log::debug('Request Uri: ' . $request->getUri());
             return $handler($request, $options);
         };
     });
     // retry
     $this->getHttp()->addMiddleware(Middleware::retry(function ($retries, RequestInterface $request, ResponseInterface $response = null, RequestException $exception = null) {
         // Limit the number of retries to 2
         if ($retries <= 2 && $response && ($body = $response->getBody())) {
             // Retry on server errors
             if (stripos($body, 'errcode') && (stripos($body, '40001') || stripos($body, '42001'))) {
                 return true;
             }
         }
         return false;
     }));
 }
 /**
  * @param  string                            $streamUrl
  * @param  EntryEmbedMode                    $embedMode
  * @return StreamFeed
  * @throws Exception\StreamDeletedException
  * @throws Exception\StreamNotFoundException
  */
 private function readStreamFeed($streamUrl, EntryEmbedMode $embedMode = null)
 {
     $request = $this->getJsonRequest($streamUrl);
     if ($embedMode != null && $embedMode != EntryEmbedMode::NONE()) {
         $uri = Uri::withQueryValue($request->getUri(), 'embed', $embedMode->toNative());
         $request = $request->withUri($uri);
     }
     $this->sendRequest($request);
     $this->ensureStatusCodeIsGood($streamUrl);
     return new StreamFeed($this->lastResponseAsJson(), $embedMode);
 }
Ejemplo n.º 13
0
 private function configureAuthenticationHandler(HandlerStack $handlerStack)
 {
     $token = $this->token;
     $handlerStack->remove('wechatClient:authentication');
     $handlerStack->unshift(function (callable $handler) use($token) {
         return function (RequestInterface $request, array $options = []) use($handler, $token) {
             if ($token) {
                 $newUri = Uri::withQueryValue($request->getUri(), 'access_token', $token->value());
                 $request = $request->withUri($newUri);
             }
             return $handler($request, $options);
         };
     }, 'wechatClient:authentication');
 }
Ejemplo n.º 14
0
 /**
  * Creates a new Request to this Endpoint.
  *
  * @param string[] $query
  * @param null     $url
  * @param string   $method
  * @param array    $options
  * @return RequestInterface
  */
 protected function createRequest(array $query = [], $url = null, $method = 'GET', $options = [])
 {
     $url = !is_null($url) ? $url : $this->url();
     $uri = new Uri($url);
     foreach ($query as $key => $value) {
         $uri = Uri::withQueryValue($uri, $key, $value);
     }
     return new Request($method, $uri, $options);
 }
 /**
  * Performs a GET against the API.
  *
  * @param string $path
  * @param array  $query
  *
  * @return ResponseInterface
  * @throw Exception\PostcodeException | Exception\ApiException | Exception\UnexpectedValueException
  */
 private function httpGet($path, array $query = array())
 {
     $url = new Uri($this->baseUrl . $path);
     foreach ($query as $name => $value) {
         $url = Uri::withQueryValue($url, $name, $value);
     }
     //---
     $request = new Request('GET', $url, $this->buildHeaders());
     try {
         $response = $this->getHttpClient()->sendRequest($request);
     } catch (\RuntimeException $e) {
         throw new Exception\PostcodeException($e->getMessage(), $e->getCode(), $e);
     }
     //---
     if ($response->getStatusCode() != 200) {
         throw $this->createErrorException($response);
     }
     return $response;
 }
 protected function getPageUrl(UriInterface $uri, $number, $query = 'page')
 {
     $url = new Url($number, Uri::withQueryValue($uri, $query, $number));
     return $url;
 }
Ejemplo n.º 17
0
 public function testAddAndRemoveQueryValues()
 {
     $uri = new Uri('http://foo.com/bar');
     $uri = Uri::withQueryValue($uri, 'a', 'b');
     $uri = Uri::withQueryValue($uri, 'c', 'd');
     $uri = Uri::withQueryValue($uri, 'e', null);
     $this->assertEquals('a=b&c=d&e', $uri->getQuery());
     $uri = Uri::withoutQueryValue($uri, 'c');
     $uri = Uri::withoutQueryValue($uri, 'e');
     $this->assertEquals('a=b', $uri->getQuery());
     $uri = Uri::withoutQueryValue($uri, 'a');
     $uri = Uri::withoutQueryValue($uri, 'a');
     $this->assertEquals('', $uri->getQuery());
 }
Ejemplo n.º 18
0
 /**
  * Adds the `lang` query parameter to the request for localized endpoints.
  *
  * @param RequestInterface $request
  *
  * @return \Psr\Http\Message\RequestInterface
  */
 public function onRequest(RequestInterface $request)
 {
     $new_uri = Uri::withQueryValue($request->getUri(), 'lang', $this->getEndpoint()->getLang());
     return $request->withUri($new_uri);
 }
Ejemplo n.º 19
0
 /**
  * @param string $rawPath
  * @param array $query
  * @param array $options
  *
  * @return Uri
  *
  * @throws \Exception
  */
 protected function resolveUri($rawPath, array $query, array $options)
 {
     $query = array_filter($query);
     $matches = [];
     preg_match_all('/[\\{]{1}([\\w]+)[\\}]{1}/', $rawPath, $matches);
     $requiredOptions = $matches[1];
     foreach ($requiredOptions as $option) {
         if (!array_key_exists($option, $options)) {
             throw new \Exception('Missing option ' . $option);
         }
         $rawPath = str_replace('{' . $option . '}', $options[$option], $rawPath);
     }
     $uri = Uri::fromParts(['scheme' => $this->clientDescription->getSchema(), 'host' => $this->clientDescription->getHost(), 'path' => $rawPath]);
     foreach ($query as $name => $value) {
         $uri = Uri::withQueryValue($uri, $name, $value);
     }
     return $uri;
 }
Ejemplo n.º 20
0
 /**
  * Return retry middleware.
  *
  * @return \GuzzleHttp\RetryMiddleware
  */
 protected function retryMiddleware()
 {
     return Middleware::retry(function ($retries, RequestInterface $request, ResponseInterface $response = null, RequestException $exception = null) {
         // Limit the number of retries to 2
         if ($retries <= 2 && $response && ($body = $response->getBody())) {
             // Retry on server errors
             if (stripos($body, 'errcode') && (stripos($body, '40001') || stripos($body, '42001'))) {
                 $field = $this->accessToken->getQueryName();
                 $token = $this->accessToken->getToken();
                 $request = $request->withUri($newUri = Uri::withQueryValue($request->getUri(), $field, $token));
                 Log::debug("Retry with Request Token: {$token}");
                 Log::debug("Retry with Request Uri: {$newUri}");
                 return true;
             }
         }
         return false;
     });
 }
Ejemplo n.º 21
0
 public function queryValueMiddleware($key, $value)
 {
     return Middleware::mapRequest(function (RequestInterface $request) use($key, $value) {
         return $request->withUri(Uri::withQueryValue($request->getUri(), $key, $value));
     });
 }
Ejemplo n.º 22
0
 public function testWithQueryValueHandlesEncoding()
 {
     $uri = new Uri();
     $uri = Uri::withQueryValue($uri, 'E=mc^2', 'ein&stein');
     $this->assertSame('E%3Dmc%5E2=ein%26stein', $uri->getQuery(), 'Decoded key/value get encoded');
     $uri = new Uri();
     $uri = Uri::withQueryValue($uri, 'E%3Dmc%5e2', 'ein%26stein');
     $this->assertSame('E%3Dmc%5e2=ein%26stein', $uri->getQuery(), 'Encoded key/value do not get double-encoded');
 }
Ejemplo n.º 23
0
 /**
  * Return the Guzzle Middleware responsible for ensuring the API key is
  * always present in a request.
  *
  * @return callable
  */
 protected function getApiKeyMiddleware()
 {
     $handleRequest = function (RequestInterface $request) {
         return $request->withUri(Uri::withQueryValue($request->getUri(), static::PARAM_API_KEY, $this->apiKey));
     };
     return Middleware::mapRequest($handleRequest);
 }
 private function meRequest($accessToken, array $fields)
 {
     $request = new Request('GET', FacebookApi::GRAPH_API_ME_URL);
     $query = $request->getUri();
     $query = Uri::withQueryValue($query, 'access_token', $accessToken);
     if (!empty($fields)) {
         $query = Uri::withQueryValue($query, 'fields', implode(',', $fields));
     }
     return $request->withUri($query);
 }
Ejemplo n.º 25
0
 /**
  * @param $object
  * @param $options
  * @return Uri
  * @throws Exception
  */
 private function prepareEndpointUri(MessageInterface $object, array $options)
 {
     $endpoint = $object->getEndpoint();
     $defaultParams = $object->getDefaultParams();
     $params = array_key_exists('params', $options) ? $options['params'] : [];
     if (substr($endpoint, 0, 4) !== 'http') {
         $endpoint = $this->apiUri . $endpoint;
     }
     $params = array_merge($params, $defaultParams);
     foreach ($params as $key => $value) {
         $endpoint = str_replace('{' . $key . '}', $value, $endpoint);
     }
     if (preg_match('/.*{.*}.*/', $endpoint)) {
         throw new Exception('Not all endpoint parameters was replaced: ' . $endpoint);
     }
     $uri = new Uri($endpoint);
     if (array_key_exists('paging', $options)) {
         $paging = $options['paging'];
         if (array_key_exists('offset', $paging)) {
             if (!is_numeric($paging['offset']) || $paging['offset'] < 0) {
                 throw new RuntimeException('Paging offset cam be only positive number and 0.');
             }
             $uri = Uri::withQueryValue($uri, 'offset', $paging['offset']);
         }
         if (array_key_exists('count', $paging)) {
             if (!is_numeric($paging['count']) || $paging['count'] < 1) {
                 throw new RuntimeException('Paging count cam be only positive number.');
             }
             $uri = Uri::withQueryValue($uri, 'count', $paging['count']);
         }
     }
     if (array_key_exists('fields', $options)) {
         if (is_array($options['fields'])) {
             $fields = implode(',', $options['fields']);
         } else {
             $fields = $options['fields'];
         }
         $uri = Uri::withQueryValue($uri, 'fields', $fields);
     }
     if (array_key_exists('exclude_fields', $options)) {
         if (array_key_exists('fields', $options)) {
             throw new RuntimeException('You can not use "fields" and "exclude_fields" in one API query.');
         }
         if (is_array($options['exclude_fields'])) {
             $exclude_fields = implode(',', $options['exclude_fields']);
         } else {
             $exclude_fields = $options['exclude_fields'];
         }
         $uri = Uri::withQueryValue($uri, 'exclude_fields', $exclude_fields);
     }
     return $uri;
 }
Ejemplo n.º 26
0
 /**
  * @param  array  $data
  * @return ServerRequest
  */
 public function getRequest(array $data = [])
 {
     $method = $this->getMethod();
     $uri = new Uri($this->getAction());
     $body = null;
     if ($this->isGet()) {
         foreach ($this->getData($data) as $key => $value) {
             $uri = Uri::withQueryValue($uri, $key, $value);
         }
     } elseif ($this->isMultipart()) {
         $body = new MultipartStream($this->getMultipartData($data), $this->getMultipartBoundary());
     } else {
         $body = http_build_query($this->getData($data), null, '&');
     }
     $request = new ServerRequest($method, $uri, $this->getHeaders(), $body);
     $files = $this->getFiles();
     return $request->withParsedBody(self::toNestedParams($this->getData($data)))->withAttribute('FILES', $files)->withUploadedFiles(ServerRequest::normalizeFiles($files));
 }
Ejemplo n.º 27
0
 /**
  * Allows pagination through the entire list of followers.
  *
  * @param string $nextOpenID - Optional ID of the next user to paginate from.
  *
  * @return PaginatedResultSet
  * @throws Exception
  */
 public function paginateUsers($nextOpenID = null)
 {
     $json = json_decode($this->client->send(new Request('GET', Uri::withQueryValue(new Uri('https://api.weixin.qq.com/cgi-bin/user/get'), 'next_openid', $nextOpenID)))->getBody());
     if (!isset($json->total)) {
         return new PaginatedResultSet(null, 0, []);
     } elseif (!isset($json->next_openid, $json->data->openid)) {
         return new PaginatedResultSet(null, $json->total, []);
     } else {
         return new PaginatedResultSet($json->next_openid ?: null, $json->total, $json->data->openid);
     }
 }
Ejemplo n.º 28
0
 /**
  * generic request executor
  *
  * @param   string          $method         GET, POST, PUT, DELETE
  * @param   string          $endpointUrl
  * @param   array           $queryString
  * @param   array|string    $body
  * @param   string          $auth           http-signatures to enable http-signature signing
  * @param   string          $contentMD5Mode body or url
  * @param   float           $timeout        timeout in seconds
  * @return Request
  */
 public function buildRequest($method, $endpointUrl, $queryString = null, $body = null, $auth = null, $contentMD5Mode = null, $timeout = null)
 {
     if (is_null($contentMD5Mode)) {
         $contentMD5Mode = !is_null($body) ? 'body' : 'url';
     }
     $request = new Request($method, $endpointUrl);
     $uri = $request->getUri();
     if ($queryString) {
         foreach ($queryString as $k => $v) {
             $uri = Uri::withQueryValue($uri, $k, $v);
         }
     }
     if (!self::hasQueryValue($uri, 'api_key')) {
         $uri = Uri::withQueryValue($uri, 'api_key', $this->apiKey);
     }
     // normalize the query string the same way the server expects it
     /** @var Request $request */
     $request = $request->withUri($uri->withQuery(\Symfony\Component\HttpFoundation\Request::normalizeQueryString($uri->getQuery())));
     if (!$request->hasHeader('Date')) {
         $request = $request->withHeader('Date', $this->getRFC1123DateString());
     }
     if (!is_null($body)) {
         if (!$request->hasHeader('Content-Type')) {
             $request = $request->withHeader('Content-Type', 'application/json');
         }
         if (!is_string($body)) {
             $body = json_encode($body);
         }
         $request = $request->withBody(\GuzzleHttp\Psr7\stream_for($body));
     }
     // for GET/DELETE requests, MD5 the request URI (excludes domain, includes query strings)
     if ($contentMD5Mode == 'body') {
         $request = $request->withHeader('Content-MD5', md5((string) $body));
     } else {
         $request = $request->withHeader('Content-MD5', md5($request->getRequestTarget()));
     }
     return $request;
 }
Ejemplo n.º 29
0
 /**
  * Performs a multipart upload to the WeChat API. Additional multipart fields can be added in if required.
  *
  * @param string   $endpoint
  * @param string   $type
  * @param resource $stream
  * @param array    $extra
  *
  * @return \stdClass
  */
 private function doMultipartUpload($endpoint, $type, $stream, array $extra = [])
 {
     return json_decode($this->client->send(new Request('POST', Uri::withQueryValue(new Uri($endpoint), 'type', $type), [], new MultipartStream(array_merge([['name' => 'media', 'contents' => $stream]], $extra))))->getBody());
 }
 /**
  * @return RequestInterface $request
  * @visible for testing
  */
 private function process()
 {
     $this->transformToUploadUrl();
     $request = $this->request;
     $postBody = '';
     $contentType = false;
     $meta = (string) $request->getBody();
     $meta = is_string($meta) ? json_decode($meta, true) : $meta;
     $uploadType = $this->getUploadType($meta);
     $request = $request->withUri(Uri::withQueryValue($request->getUri(), 'uploadType', $uploadType));
     $mimeType = $this->mimeType ? $this->mimeType : $request->getHeaderLine('content-type');
     if (self::UPLOAD_RESUMABLE_TYPE == $uploadType) {
         $contentType = $mimeType;
         $postBody = is_string($meta) ? $meta : json_encode($meta);
     } else {
         if (self::UPLOAD_MEDIA_TYPE == $uploadType) {
             $contentType = $mimeType;
             $postBody = $this->data;
         } else {
             if (self::UPLOAD_MULTIPART_TYPE == $uploadType) {
                 // This is a multipart/related upload.
                 $boundary = $this->boundary ? $this->boundary : mt_rand();
                 $boundary = str_replace('"', '', $boundary);
                 $contentType = 'multipart/related; boundary=' . $boundary;
                 $related = "--{$boundary}\r\n";
                 $related .= "Content-Type: application/json; charset=UTF-8\r\n";
                 $related .= "\r\n" . json_encode($meta) . "\r\n";
                 $related .= "--{$boundary}\r\n";
                 $related .= "Content-Type: {$mimeType}\r\n";
                 $related .= "Content-Transfer-Encoding: base64\r\n";
                 $related .= "\r\n" . base64_encode($this->data) . "\r\n";
                 $related .= "--{$boundary}--";
                 $postBody = $related;
             }
         }
     }
     $request = $request->withBody(Psr7\stream_for($postBody));
     if (isset($contentType) && $contentType) {
         $request = $request->withHeader('content-type', $contentType);
     }
     return $this->request = $request;
 }