public function getModel($make, $model, array $options = []) { $resolver = new OptionsResolver(); $resolver->setDefaults(['year' => 1990, 'view' => 'basic']); $resolver->setDefined('state'); $resolver->setRequired(['state', 'view']); $resolver->setAllowedTypes('year', 'integer'); $resolver->setAllowedValues('state', ['new', 'used']); $resolver->setDefault('state', function (Options $options, $previousValue) { if ($options['year'] >= 2015) { return 'new'; } return $previousValue; }); // $resolver->isDefined('state'); $options = $resolver->resolve($options); $client = new GuzzleHttp\Client(); $queryParams = array_merge($options, ['fmt' => 'json', 'api_key' => $this->apiKey]); $query = GuzzleHttp\Psr7\build_query($queryParams); $request = new GuzzleHttp\Psr7\Request('GET', $this->apiEndpoint . $make . '/' . $model . '?' . $query); /** @var ResponseInterface $response */ $response = $client->send($request); if ($this->dispatcher) { $this->dispatcher->dispatch(ApiCallEvent::EVENT_NAME, new GenericEvent($this, ['make' => $make, 'model' => $model, 'options' => $options])); } return $this->delegatingSerializer->deserialize($response->getBody(), 'json', ['type' => 'array']); }
/** * @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); }
public function get_logout_link($returnTo = null, $client_id = null) { $params = []; if ($returnTo !== null) { $params['returnTo'] = $returnTo; } if ($client_id !== null) { $params['client_id'] = $client_id; } $query_string = Psr7\build_query($params); return "https://{$this->domain}/v2/logout?{$query_string}"; }
/** * @param string $uri * @param array $query * @return UriInterface */ public function buildUriWithQuery($uri, array $query) { // @todo fix this hack. when using build_query booleans are converted to // 1 or 0 which the API does not accept. this casts bools to their // string representation $query = array_filter($query); foreach ($query as $k => &$v) { if (is_bool($v)) { $v = $v ? 'true' : 'false'; } } return Psr7\uri_for($uri)->withQuery(Psr7\build_query($query)); }
public function getMakes($state, $year, $view = 'full') { $client = new GuzzleHttp\Client(); $query = GuzzleHttp\Psr7\build_query(['api_key' => $this->apiKey, 'state' => $state, 'year' => $year, 'view' => $view, 'fmt' => 'json']); /** @var ResponseInterface $result */ $result = $client->request('GET', $this->apiEndpoint . self::API_METHOD . '?' . $query); if ($this->logger) { $this->logger->log(LogLevel::INFO, sprintf('Makes response : %s', $result->getBody())); } if ($this->dispatcher) { $this->dispatcher->dispatch(ApiCallEvent::EVENT_NAME, new GenericEvent($this, ['state' => $state, 'year' => $year, 'view' => $view])); } return $this->delegatingSerializer->deserialize((string) $result->getBody(), 'json', ['type' => 'array']); }
/** * Updates the request query with the developer key if auth is set to simple * * use Google\Auth\Middleware\SimpleMiddleware; * use GuzzleHttp\Client; * use GuzzleHttp\HandlerStack; * * $my_key = 'is not the same as yours'; * $middleware = new SimpleMiddleware(['key' => $my_key]); * $stack = HandlerStack::create(); * $stack->push($middleware); * * $client = new Client([ * 'handler' => $stack, * 'base_uri' => 'https://www.googleapis.com/discovery/v1/', * 'auth' => 'simple' * ]); * * $res = $client->get('drive/v2/rest'); */ public function __invoke(callable $handler) { return function (RequestInterface $request, array $options) use($handler) { // Requests using "auth"="scoped" will be authorized. if (!isset($options['auth']) || $options['auth'] !== 'simple') { return $handler($request, $options); } $query = Psr7\parse_query($request->getUri()->getQuery()); $params = array_merge($query, $this->config); $uri = $request->getUri()->withQuery(Psr7\build_query($params)); $request = $request->withUri($uri); return $handler($request, $options); }; }
/** * Create a pre-signed URL for Polly operation `SynthesizeSpeech` * * @param array $args parameters array for `SynthesizeSpeech` * More information @see Aws\Polly\PollyClient::SynthesizeSpeech * * @return string */ public function createSynthesizeSpeechPreSignedUrl(array $args) { $uri = new Uri($this->getEndpoint()); $uri = $uri->withPath('/v1/speech'); // Formatting parameters follows rest-json protocol $this->formatter = $this->formatter ?: new JsonBody($this->getApi()); $queryArray = json_decode($this->formatter->build($this->getApi()->getOperation('SynthesizeSpeech')->getInput(), $args), true); // Mocking a 'GET' request in pre-signing the Url $query = Psr7\build_query($queryArray); $uri = $uri->withQuery($query); $request = new Request('GET', $uri); $request = $request->withBody(Psr7\stream_for('')); $signer = new SignatureV4('polly', $this->getRegion()); return (string) $signer->presign($request, $this->getCredentials()->wait(), '+15 minutes')->getUri(); }
public function testDoesNotEncode() { $str = Psr7\build_query(['foo bar' => 'baz+'], false); $this->assertEquals('foo bar=baz+', $str); }
/** * Sends HTTP request with the specified parameters. * * @param string $method HTTP method used in the request * @param array $headers HTTP headers. * @param array $queryParams URL query parameters. * @param array $postParameters The HTTP POST parameters. * @param string $path URL path * @param int $statusCode Expected status code received in the response * @param string $body Request body * @param array $clientOptions Guzzle Client options * * @return GuzzleHttp\Psr7\Response */ protected function send($method, $headers, $queryParams, $postParameters, $path, $statusCode, $body = Resources::EMPTY_STRING) { // add query parameters into headers $uri = $this->_psrUri; if ($path != NULL) { $uri = $uri->withPath($path); } if ($queryParams != NULL) { $queryString = Psr7\build_query($queryParams); $uri = $uri->withQuery($queryString); } // add post parameters into bodys $actualBody = NULL; if (empty($body)) { if (empty($headers['content-type'])) { $headers['content-type'] = 'application/x-www-form-urlencoded'; $actualBody = Psr7\build_query($postParameters); } } else { $actualBody = $body; } $request = new Request($method, $uri, $headers, $actualBody); $client = new \GuzzleHttp\Client(array_merge($this->_options['http'], array("defaults" => array("allow_redirects" => true, "exceptions" => true, "decode_content" => true), 'cookies' => true, 'verify' => false))); $bodySize = $request->getBody()->getSize(); if ($bodySize > 0) { $request = $request->withHeader('content-length', $bodySize); } // Apply filters to the requests foreach ($this->getFilters() as $filter) { $request = $filter->handleRequest($request); } try { $response = $client->send($request); self::throwIfError($response->getStatusCode(), $response->getReasonPhrase(), $response->getBody(), $statusCode); return $response; } catch (\GuzzleHttp\Exception\RequestException $e) { if ($e->hasResponse()) { $response = $e->getResponse(); self::throwIfError($response->getStatusCode(), $response->getReasonPhrase(), $response->getBody(), $statusCode); return $response; } else { throw $e; } } }
/** * Builds the authorization Uri that the user should be redirected to. * * @param array $config configuration options that customize the return url * * @return UriInterface the authorization Url. * * @throws InvalidArgumentException */ public function buildFullAuthorizationUri(array $config = []) { if (is_null($this->getAuthorizationUri())) { throw new InvalidArgumentException('requires an authorizationUri to have been set'); } $params = array_merge(['response_type' => 'code', 'access_type' => 'offline', 'client_id' => $this->clientId, 'redirect_uri' => $this->redirectUri, 'state' => $this->state, 'scope' => $this->getScope()], $config); // Validate the auth_params if (is_null($params['client_id'])) { throw new InvalidArgumentException('missing the required client identifier'); } if (is_null($params['redirect_uri'])) { throw new InvalidArgumentException('missing the required redirect URI'); } if (!empty($params['prompt']) && !empty($params['approval_prompt'])) { throw new InvalidArgumentException('prompt and approval_prompt are mutually exclusive'); } // Construct the uri object; return it if it is valid. $result = clone $this->authorizationUri; $existingParams = Psr7\parse_query($result->getQuery()); $result = $result->withQuery(Psr7\build_query(array_merge($existingParams, $params))); if ($result->getScheme() != 'https') { throw new InvalidArgumentException('Authorization endpoint must be protected by TLS'); } return $result; }
private function buildRequest(array $req) { if ($req['query']) { $req['uri'] = $req['uri']->withQuery(Psr7\build_query($req['query'])); } return new Psr7\Request($req['method'], $req['uri'], $req['headers'], $req['body'], $req['version']); }
private function buildEndpoint(Operation $operation, array $args, array $opts) { $varspecs = []; // Create an associative array of varspecs used in expansions foreach ($operation->getInput()->getMembers() as $name => $member) { if ($member['location'] == 'uri') { $varspecs[$member['locationName'] ?: $name] = isset($args[$name]) ? $args[$name] : null; } } $relative = preg_replace_callback('/\\{([^\\}]+)\\}/', function (array $matches) use($varspecs) { $isGreedy = substr($matches[1], -1, 1) == '+'; $k = $isGreedy ? substr($matches[1], 0, -1) : $matches[1]; if (!isset($varspecs[$k])) { return ''; } elseif ($isGreedy) { return str_replace('%2F', '/', rawurlencode($varspecs[$k])); } else { return rawurlencode($varspecs[$k]); } }, $operation['http']['requestUri']); // Add the query string variables or appending to one if needed. if (!empty($opts['query'])) { $append = Psr7\build_query($opts['query']); $relative .= strpos($relative, '?') ? "&{$append}" : "?{$append}"; } // Expand path place holders using Amazon's slightly different URI // template syntax. return Psr7\Uri::resolve($this->endpoint, $relative); }
/** * @param CommandInterface $command * * @return RequestInterface */ public function commandToRequestTransformer(CommandInterface $command) { $name = $command->getName(); if (!isset($this->api[$name])) { throw new CommandException('Command not found', $command); } $action = $this->api[$name]; $prefix = ''; if (isset($action['public']) && $command->hasParam('public')) { $prefix = '/public'; } $prefixes = ['system' => '/systems/{system}', 'issuer' => '/issuers/{issuer}', 'program' => '/programs/{program}']; if (isset($action['admin_contexts'])) { $prefix .= implode('', array_intersect_key($prefixes, array_flip($action['admin_contexts']), array_merge($command->toArray(), $this->adminContext))); } $path = GuzzleHttp\uri_template($prefix . $action['path'], array_merge($command->toArray(), $this->adminContext)); $headers = []; $body = null; if ($command->hasParam('body')) { $headers = ['Content-Type' => 'application/json']; $body = GuzzleHttp\json_encode($command['body']); } if ($command->hasParam('query')) { $path .= '?' . Psr7\build_query($command['query']); } return new Psr7\Request($action['method'], $path, $headers, $body); }
/** * Helper method to generate an alternative form of an URL, where array indices have either * been added or removed. foo[] is transformed into foo[0], while foo[0] is transformed into foo[]. * * The result for URLs with both formats is undefined, or for URLs that intermingle their parameters, * i.e. t[]=foo&b[]=bar&t[]=baz * * This was introduced because of differences between the URLs generated by the different clients, and * because Facebook (at least) generates URLs were []s in URL arguments are expanded to [0] when * requested from the backend. Since we sign our URLs, this breaks the token generation and thus breaks * URLs when Facebook attempts to retrieve them. * * @param string $url The URL to generate the alternative form of * @param int $encoding The encoding to use - from GuzzleHttp\Psr7 * @return string */ protected function getAlternativeURL($url, $encoding = PHP_QUERY_RFC3986) { $urlParts = parse_url($url); if (!isset($urlParts['query'])) { return $url; } $queryString = $urlParts['query']; $fixKeyPattern = '#\\[[0-9]+\\]$#'; $parsed = Psr7\parse_query($queryString); $newArguments = array(); foreach ($parsed as $key => $value) { $fixedKey = preg_replace($fixKeyPattern, '', $key); // if the key came out different, we're talking about a t[x] format - so we store those // to allow for the correct sequence when regenerating the URL further below. if ($fixedKey != $key) { $fixedKey .= '[]'; if (!isset($newArguments[$fixedKey])) { $newArguments[$fixedKey] = array(); } $newArguments[$fixedKey][] = $value; } else { if (is_array($value) && substr($key, -2) == '[]') { // if the value is an array, and we have the [] format already, we expand the keys foreach ($value as $innerKey => $innerValue) { // remove [] from the key and append the inner array key $indexedKey = substr($key, 0, -2) . '[' . $innerKey . ']'; $newArguments[$indexedKey] = $innerValue; } } else { $newArguments[$key] = $value; } } } $urlParts['query'] = Psr7\build_query($newArguments, $encoding); $url = Urls::buildFromParseUrlParts($urlParts); return $url; }
/** * Build a query string from an array of key value pairs * * @param array $params Query string parameters. * @param int|false $encoding Set to false to not encode, PHP_QUERY_RFC3986 * to encode using RFC3986, or PHP_QUERY_RFC1738 * to encode using RFC1738. * @return string */ public function buildQuery(array $params, $encoding = PHP_QUERY_RFC3986) { return Psr7\build_query($params, $encoding); }
/** * @param string $method * @param string $url * @param array $options * * @return RequestInterface */ protected function buildRequest($method, $url, array $options = []) { $uri = new Uri($url); $request = new Request($method, $uri); foreach ($options as $key => $optValue) { switch ($key) { case 'query': if (is_array($optValue)) { $optValue = build_query($optValue); } $uri = $uri->withQuery($optValue); $request = $request->withUri($uri); break; case 'headers': foreach ($optValue as $headerName => $headerValue) { $request = $request->withHeader($headerName, $headerValue); } break; case 'body': $request = $request->withBody(stream_for($optValue)); break; } } return $request; }