/** * Expand config array with URI endpoint * * @param array $config * @param array $args * * @return array */ private function expand(array $config, array $args) { $scheme = isset($args['scheme']) ? $args['scheme'] : 'https'; $config['endpoint'] = $scheme . '://' . Utils::uriTemplate($config['endpoint'], $args); return $config; }
/** * Automatically set global configuration if provided * * @param InitEvent $event */ public function onInit(InitEvent $event) { $command = $event->getCommand(); $operation = $this->description->getOperation($command->getName()); // For touristic object methods only if (in_array($operation->getName(), ['searchObject', 'searchObjectIdentifier', 'searchAgenda', 'searchAgendaIdentifier', 'searchDetailedAgendaIdentifier', 'searchDetailedAgenda'])) { $data = is_array($command['query']) ? $command['query'] : Utils::jsonDecode($command['query'], true); if (!empty($this->config['responseFields']) && !isset($data['responseFields'])) { $data['responseFields'] = $this->config['responseFields']; } if (!empty($this->config['locales']) && !isset($data['locales'])) { $data['locales'] = $this->config['locales']; } if (!empty($this->config['count']) && !isset($data['count'])) { $data['count'] = $this->config['count']; } $command['query'] = json_encode($data); } else { if ($operation->hasParam('locales') && !isset($command['locales'])) { $command['locales'] = implode(',', $this->config['locales']); } if ($operation->hasParam('responseFields') && !isset($command['responseFields'])) { $command['responseFields'] = implode(',', $this->config['responseFields']); } } }
public function json(array $config = []) { try { return Utils::jsonDecode((string) $this->getBody(), isset($config['object']) ? !$config['object'] : true, 512, isset($config['big_int_strings']) ? JSON_BIGINT_AS_STRING : 0); } catch (\InvalidArgumentException $e) { throw new ParseException($e->getMessage(), $this); } }
/** * {@inheritdoc} */ public function format($response) { try { $response = \GuzzleHttp\Utils::jsonDecode($response); return json_encode($response, JSON_PRETTY_PRINT); } catch (\Exception $e) { return $response; } }
/** * Creates a message object from the raw POST data * * @return Message * @throws \RuntimeException If the POST data is absent, or not a valid JSON document */ public static function fromRawPostData() { if (!isset($_SERVER['HTTP_X_AMZ_SNS_MESSAGE_TYPE'])) { throw new \RuntimeException('SNS message type header not provided.'); } $data = Utils::jsonDecode(file_get_contents('php://input'), true); if (!is_array($data)) { throw new \RuntimeException('POST data invalid'); } return self::fromArray($data); }
/** * Load the contents of the client session into the data array */ protected function load() { $cookieJar = isset($_SESSION[$this->sessionKey]) ? $_SESSION[$this->sessionKey] : null; $data = Utils::jsonDecode($cookieJar, true); if (is_array($data)) { foreach ($data as $cookie) { $this->setCookie(new SetCookie($cookie)); } } elseif (strlen($data)) { throw new \RuntimeException("Invalid cookie data"); } }
public function testSetupFieldList() { $json = Utils::jsonDecode($this->json, true, 512, JSON_BIGINT_AS_STRING); $properties = $json['properties']; $fields = new FieldList($properties); $this->assertCount(3, $fields); $labels = []; foreach ($fields as $field) { $labels[] = $field->getLabel(); } $expectedLabels = ["string_1", "number_1", "checkbox_1"]; $this->assertEquals($expectedLabels, $labels); }
/** * Downloads, unzips, and reads a CloudTrail log file from Amazon S3 * * @param string $s3BucketName The bucket name of the log file in Amazon S3 * @param string $logFileKey The key of the log file in Amazon S3 * * @return array */ public function read($s3BucketName, $logFileKey) { // Create a command for getting the log file object $command = $this->s3Client->getCommand('GetObject', array('Bucket' => (string) $s3BucketName, 'Key' => (string) $logFileKey, 'ResponseContentEncoding' => 'x-gzip')); // Make sure gzip encoding header is sent and accepted in order to // inflate the response data. $command->getEmitter()->on('prepared', function (PreparedEvent $e) { $e->getRequest()->setHeader('Accept-Encoding', 'gzip'); }, RequestEvents::LATE); // Get the JSON response data and extract the log records $result = $this->s3Client->execute($command); $logData = Utils::jsonDecode($result['Body'], true); return isset($logData['Records']) ? $logData['Records'] : []; }
/** * Load cookies from a JSON formatted file. * * Old cookies are kept unless overwritten by newly loaded ones. * * @param string $filename Cookie file to load. * @throws \RuntimeException if the file cannot be loaded. */ public function load($filename) { $json = file_get_contents($filename); if (false === $json) { // @codeCoverageIgnoreStart throw new \RuntimeException("Unable to load file {$filename}"); // @codeCoverageIgnoreEnd } $data = Utils::jsonDecode($json, true); if (is_array($data)) { foreach (Utils::jsonDecode($json, true) as $cookie) { $this->setCookie(new SetCookie($cookie)); } } elseif (strlen($data)) { throw new \RuntimeException("Invalid cookie file: {$filename}"); } }
/** * Loads refreshable profile credentials if they are available, otherwise * returns null. * * @return RefreshableCredentials|null */ public function __invoke() { // Pass if the profile cannot be loaded or was not provided. if (!$this->profile) { try { $this->profile = $this->request('meta-data/iam/security-credentials/'); } catch (CredentialsException $e) { return null; } } return new RefreshableCredentials(function () { $response = $this->request("meta-data/iam/security-credentials/{$this->profile}"); $result = Utils::jsonDecode($response, true); if ($result['Code'] !== 'Success') { throw new CredentialsException('Unexpected instance profile response' . " code: {$result['Code']}"); } return new Credentials($result['AccessKeyId'], $result['SecretAccessKey'], $result['Token'], strtotime($result['Expiration'])); }); }
/** * Automatically set apiKey & projetId query parameters when needed * * @param InitEvent $event */ public function onInit(InitEvent $event) { $command = $event->getCommand(); $operation = $this->description->getOperation($command->getName()); if ($operation->hasParam('apiKey') && !isset($command['apiKey'])) { $command['apiKey'] = $this->config['apiKey']; } if ($operation->hasParam('projetId') && !isset($command['projetId'])) { $command['projetId'] = $this->config['projectId']; } // Search operations use the authentication inside a query string JSON! if (in_array($operation->getName(), ['searchObject', 'searchObjectIdentifier', 'searchAgenda', 'searchAgendaIdentifier', 'searchDetailedAgendaIdentifier', 'searchDetailedAgenda', 'getReferenceCity', 'getReferenceElement', 'getReferenceInternalCriteria', 'getReferenceSelection'])) { $data = is_array($command['query']) ? $command['query'] : Utils::jsonDecode($command['query'], true); if (!isset($data['apiKey']) && !isset($data['projetId'])) { $data['apiKey'] = $this->config['apiKey']; $data['projetId'] = $this->config['projectId']; $command['query'] = json_encode($data); } } }
/** * @inheritdoc */ public function register(Application $app) { if (!isset($app['guzzle.base_url'])) { $app['guzzle.base_url'] = '/'; } if (!isset($app['guzzle.handler'])) { $app['guzzle.handler'] = Utils::getDefaultHandler(); } if (!isset($app['guzzle.message_factory'])) { $app['guzzle.message_factory'] = new MessageFactory(); } if (!isset($app['guzzle.defaults'])) { $app['guzzle.defaults'] = []; } if (!isset($app['guzzle.emitter'])) { $app['guzzle.emitter'] = new Emitter(); } $app['guzzle.client'] = function ($app) { return new Client(array('base_url' => $app['guzzle.base_url'], 'message_factory' => $app['guzzle.message_factory'], 'defaults' => $app['guzzle.defaults'], 'emitter' => $app['guzzle.emitter'])); }; }
public function __construct(RequestException $e) { $this->request = $e->getRequest(); $this->response = $e->getResponse(); $simpleMessage = $e->getMessage(); $code = 0; if ($this->response) { try { $decodedJson = Utils::jsonDecode((string) $this->response->getBody(), true); if ($decodedJson && isset($decodedJson['errorType'])) { $simpleMessage = $decodedJson['errorType'] . ' ' . $decodedJson['message']; } } catch (\InvalidArgumentException $e) { // Not Json } $code = $this->response->getStatusCode(); } $responseDescription = $this->response ? (string) $this->response : 'none'; $requestDescription = $this->request ? (string) $this->request : 'none'; $message = sprintf("%s\n\nRequest: %s\n\nResponse: %s\n\n", $simpleMessage, $requestDescription, $responseDescription); parent::__construct($message, $code, $e); }
/** * @deprecated Use GuzzleHttp\Utils::getDefaultUserAgent */ public static function getDefaultUserAgent() { return Utils::getDefaultUserAgent(); }
public function testProvidesDefaultUserAgent() { $ua = Utils::getDefaultUserAgent(); $this->assertEquals(1, preg_match('#^Guzzle/.+ curl/.+ PHP/.+$#', $ua)); }
private function handleClient($value, array &$args) { if (!$value instanceof ClientInterface) { throw new InvalidArgumentException('client must be an instance of GuzzleHttp\\ClientInterface, ' . get_class($value) . ' passed'); } if (isset($args['defaults']) && is_array($args)) { foreach ($args['defaults'] as $defaultName => $defaultValue) { $args['client']->setDefaultOption($defaultName, $defaultValue); } } // Make sure the user agent is prefixed by the SDK version $args['client']->setDefaultOption('headers/User-Agent', 'sellercenter-sdk-php/' . Sdk::VERSION . ' ' . Utils::getDefaultUserAgent()); }
private function load($service, $version, $type) { // First check for PHP files, then fall back to JSON. $path = "{$this->path}/{$service}-{$version}.{$type}.php"; if (file_exists($path)) { /** @noinspection PhpIncludeInspection */ return require $path; } $path = "{$this->path}/{$service}-{$version}.{$type}.json"; if (file_exists($path)) { return Utils::jsonDecode(file_get_contents($path), true); } throw new \RuntimeException('Cannot load file: ' . $path); }
/** * Returns the Guzzle client configured according to the system environment * (e.g. it takes into account whether it should use a proxy server or not). * * @return Client The configured Guzzle client * * @throws \RuntimeException If the php-curl is not installed or the allow_url_fopen ini setting is not set */ protected function getGuzzleClient() { $defaults = array(); // check if the client must use a proxy server if (!empty($_SERVER['HTTP_PROXY']) || !empty($_SERVER['http_proxy'])) { $defaults['proxy'] = !empty($_SERVER['http_proxy']) ? $_SERVER['http_proxy'] : $_SERVER['HTTP_PROXY']; } if ($this->output->getVerbosity() >= OutputInterface::VERBOSITY_DEBUG) { $defaults['debug'] = true; } try { $handler = Utils::getDefaultHandler(); } catch (\RuntimeException $e) { throw new \RuntimeException('The Symfony installer requires the php-curl extension or the allow_url_fopen ini setting.'); } return new Client(array('defaults' => $defaults, 'handler' => $handler)); }
/** * @expectedException \InvalidArgumentException * @expectedExceptionMessage Unable to parse JSON data: JSON_ERROR_SYNTAX - Syntax error, malformed JSON */ public function testJsonDecodesWithErrorMessages() { Utils::jsonDecode('!narf!'); }
private function configureBaseUrl(&$config) { if (!isset($config['base_url'])) { $this->baseUrl = new Url('', ''); } elseif (!is_array($config['base_url'])) { $this->baseUrl = Url::fromString($config['base_url']); } elseif (count($config['base_url']) < 2) { throw new \InvalidArgumentException('You must provide a hash of ' . 'varname options in the second element of a base_url array.'); } else { $this->baseUrl = Url::fromString(Utils::uriTemplate($config['base_url'][0], $config['base_url'][1])); $config['base_url'] = (string) $this->baseUrl; } }
/** * Create a request for an operation with a uri merged onto a base URI */ private function createCommandWithUri(Operation $operation, CommandInterface $command, ServiceClientInterface $client) { // Get the path values and use the client config settings $variables = []; foreach ($operation->getParams() as $name => $arg) { /* @var Parameter $arg */ if ($arg->getLocation() == 'uri') { if (isset($command[$name])) { $variables[$name] = $arg->filter($command[$name]); if (!is_array($variables[$name])) { $variables[$name] = (string) $variables[$name]; } } } } // Expand the URI template. $uri = Utils::uriTemplate($operation->getUri(), $variables); return $client->getHttpClient()->createRequest($operation->getHttpMethod(), $this->description->getBaseUrl()->combine($uri), $command['request_options'] ?: []); }
/** * This method will take all of the user-provided values and populate them into a * {@see \GuzzleHttp\Message\RequestInterface} object according to each parameter schema. * Headers and URL query parameters will be set, along with the JSON body. * * In other words, it allows for the easy creation of a fully populated HTTP request in * accordance with the expectations of the remote API. * * @return \GuzzleHttp\Message\RequestInterface * @throws \Exception */ public function createRequest() { $this->validate($this->userValues); $options = ['exceptions' => false]; if (!empty($json = $this->serializeJson())) { $options['json'] = $json; } if (!empty($body = $this->serializeBody())) { $options['body'] = $body; } if (!empty($headers = $this->serializeHeaders())) { $options['headers'] = $headers; } $url = $this->serializeQuery(Utils::uriTemplate($this->path, $this->userValues)); return $this->client->createRequest($this->method, $url, $options); }
/** * Load the file containing the API data for the given type/service/version. */ private function loadApiData($type, $service, $version) { // First check for PHP files, then fall back to JSON. $path = "{$this->modelsDir}/{$service}-{$version}.{$type}.php"; if (file_exists($path)) { return require $path; } $path = "{$this->modelsDir}/{$service}-{$version}.{$type}.json"; if (file_exists($path)) { return Utils::jsonDecode(file_get_contents($path), true); } return null; }
public function testAddsDefaultUserAgentHeaderWithoutDefaultOptions() { $client = new Client(); $this->assertEquals(['User-Agent' => Utils::getDefaultUserAgent()], $client->getDefaultOption('headers')); }
public function getConfig($keyOrPath = null) { if ($keyOrPath === null) { return $this->config; } if (strpos($keyOrPath, '/') === false) { return isset($this->config[$keyOrPath]) ? $this->config[$keyOrPath] : null; } return Utils::getPath($this->config, $keyOrPath); }
private function configureBaseUrl(&$config) { if (!isset($config['base_url'])) { $this->baseUrl = new Url('', ''); } elseif (is_array($config['base_url'])) { $this->baseUrl = Url::fromString(Utils::uriTemplate($config['base_url'][0], $config['base_url'][1])); $config['base_url'] = (string) $this->baseUrl; } else { $this->baseUrl = Url::fromString($config['base_url']); } }