/** * @param type $baseUrl * @param type $config * @return \Guzzle\Http\Client */ public function getGuzzleClient($baseUrl = '', $config = null) { if (!is_null($config)) { $this->config->merge($config); } return new Client($baseUrl, $this->config); }
/** * Create a new Response based on a raw response message * * @param string $message Response message * * @return Response * @throws InvalidArgumentException if an empty $message is provided */ public static function fromMessage($message) { if (!$message) { throw new InvalidArgumentException('No response message provided'); } // Normalize line endings $message = preg_replace("/([^\r])(\n)\\b/", "\$1\r\n", $message); $protocol = $code = $status = ''; $parts = explode("\r\n\r\n", $message, 2); $headers = new Collection(); foreach (array_values(array_filter(explode("\r\n", $parts[0]))) as $i => $line) { // Remove newlines from headers $line = implode(' ', explode("\n", $line)); if ($i === 0) { // Check the status line list($protocol, $code, $status) = array_map('trim', explode(' ', $line, 3)); } else { if (strpos($line, ':')) { // Add a header list($key, $value) = array_map('trim', explode(':', $line, 2)); // Headers are case insensitive $headers->add($key, $value); } } } $body = null; if (isset($parts[1]) && $parts[1] != "\n") { $body = EntityBody::factory(trim($parts[1])); // Always set the appropriate Content-Length if Content-Legnth $headers['Content-Length'] = $body->getSize(); } $response = new static(trim($code), $headers, $body); $response->setProtocol($protocol)->setStatus($code, $status); return $response; }
/** * Request before-send event handler. * * @param \Guzzle\Common\Event $event */ public function onRequestBeforeSend(Event $event) { $apiKey = $this->config->get('api_key'); $username = $this->config->get('username'); $password = $this->config->get('password'); $this->addApiKey($event['request'], $apiKey)->addAuthorizationHeader($event['request'], $username, $password); }
/** * @param CredentialsInterface $credentials AWS credentials * @param SignatureInterface $signature Signature implementation * @param Collection $config Configuration options * * @throws InvalidArgumentException if an endpoint provider isn't provided */ public function __construct(CredentialsInterface $credentials, SignatureInterface $signature, Collection $config) { // Use the system's CACert if running as a phar if (defined('AWS_PHAR')) { $config->set(self::SSL_CERT_AUTHORITY, 'system'); } // Bootstrap with Guzzle parent::__construct($config->get(Options::BASE_URL), $config); $this->credentials = $credentials; $this->signature = $signature; $this->endpointProvider = $config->get(Options::ENDPOINT_PROVIDER); // Make sure an endpoint provider was provided in the config if (!$this->endpointProvider instanceof EndpointProviderInterface) { throw new InvalidArgumentException('An endpoint provider must be provided to instantiate an AWS client'); } // Make sure the user agent is prefixed by the SDK version $this->setUserAgent('aws-sdk-php2/' . Aws::VERSION, true); // Set the service description on the client $this->addServiceDescriptionFromConfig(); // Add the event listener so that requests are signed before they are sent $this->getEventDispatcher()->addSubscriber(new SignatureListener($credentials, $signature)); // Resolve any config options on the client that require a client to be instantiated $this->resolveOptions(); // Add a resource iterator factory that uses the Iterator directory $this->addDefaultResourceIterator(); }
/** * @param Collection $headers * @return array */ private function headerCollectionToArray(Collection $headers) { $headers_arr = array(); foreach ($headers->toArray() as $name => $val) { $headers_arr[$name] = current($val); } return $headers_arr; }
/** * {@inheritdoc} */ public static function fromCommand(OperationCommand $command) { $activities = new Collection(); foreach ($command->getResponse()->json() as $key => $activity) { $activities->add($key, self::hydrateModelProperties(new self(), $activity)); } return $activities; }
/** * Default method to execute when credentials are not specified * * @param Collection $config Config options * * @return CredentialsInterface */ protected function defaultMissingFunction(Collection $config) { if ($config->get(Options::KEY) && $config->get(Options::SECRET)) { // Credentials were not provided, so create them using keys return Credentials::factory($config->getAll()); } // Attempt to get credentials from the EC2 instance profile server return new RefreshableInstanceProfileCredentials(new Credentials('', '', '', 1)); }
public function __construct($apiKey, ParametersEscaper $parametersEscaper, $environment) { $this->apiKey = $apiKey; $this->parametersEscaper = $parametersEscaper; $this->environment = $environment; $headers = new Collection(); $headers->add('X-HTTP-Method-Override', 'GET'); $this->client = new Client(); $this->client->setDefaultHeaders($headers); }
/** * @param string $group * * @return string */ public function getConfigFilename($group) { $conf_files = $this->config->get('conf_files'); if (!isset($conf_files[$group])) { $filename = $this->config['conf_dir'] . '/' . $group . '.json'; $conf_files[$group] = $filename; } $this->config->set('conf_files', $conf_files); return $conf_files[$group]; }
/** * Collects items from the result of a DynamoDB operation and returns them as an ItemIterator. * * @param Collection $result The result of a DynamoDB operation that potentially contains items * (e.g., BatchGetItem, DeleteItem, GetItem, PutItem, Query, Scan, UpdateItem) * * @return self */ public static function fromResult(Collection $result) { if (!($items = $result->get('Items'))) { if ($item = $result->get('Item') ?: $result->get('Attributes')) { $items = array($item); } else { $items = $result->getPath('Responses/*'); } } return new self(new \ArrayIterator($items ?: array())); }
/** * {@inheritdoc} */ public static function fromCommand(OperationCommand $command) { $data = $command->getResponse()->json(); $records = new Collection(); if (isset($data['records']) && is_array($data['records'])) { foreach ($data['records'] as $key => $object) { $records->add($key, self::hydrateModelProperties(new ReferencingApplicationFindResult(), $object, array('applicationUuid' => 'referencingApplicationUuId'))); } } $instance = self::hydrateModelProperties(new self(), $data, array(), array('records' => $records)); return $instance; }
/** * Create a Cookie by parsing a Cookie HTTP header * * @param string $cookieString Cookie HTTP header * * @return Cookie */ public static function factory($cookieString) { $data = new Collection(); if ($cookieString) { foreach (explode(';', $cookieString) as $kvp) { $parts = explode('=', $kvp, 2); $key = urldecode(trim($parts[0])); $value = isset($parts[1]) ? trim($parts[1]) : ''; $data->add($key, urldecode($value)); } } return new static($data->getAll()); }
/** * Validate and prepare configuration parameters * * @param array $config Configuration values to apply. * @param array $defaults Default parameters * @param array $required Required parameter names * * @return Collection * @throws InvalidArgumentException if a parameter is missing */ public static function prepareConfig(array $config = null, array $defaults = null, array $required = null) { $collection = new Collection($defaults); foreach ((array) $config as $key => $value) { $collection->set($key, $value); } foreach ((array) $required as $key) { if ($collection->hasKey($key) === false) { throw new ValidationException("Config must contain a '{$key}' key"); } } return $collection; }
/** * {@inheritdoc} */ public static function fromCommand(OperationCommand $command) { $data = $command->getResponse()->json(); // Collection of notes if (self::isResponseDataIndexedArray($data)) { $notes = new Collection(); foreach ($data as $key => $noteData) { $notes->add($key, self::hydrateModelProperties(new self(), $noteData)); } return $notes; } else { return self::hydrateModelProperties(new self(), $data); } }
public function testConstructorCallsResolvers() { $config = new Collection(array(Options::ENDPOINT_PROVIDER => $this->getMock('Aws\\Common\\Region\\EndpointProviderInterface'))); $signature = new SignatureV4(); $credentials = new Credentials('test', '123'); $config->set('client.resolvers', array(new BackoffOptionResolver(function () { return BackoffPlugin::getExponentialBackoff(); }))); $client = $this->getMockBuilder('Aws\\Common\\Client\\AbstractClient')->setConstructorArgs(array($credentials, $signature, $config))->getMockForAbstractClass(); // Ensure that lazy resolvers were triggered $this->assertInstanceOf('Guzzle\\Plugin\\Backoff\\BackoffPlugin', $client->getConfig(Options::BACKOFF)); // Ensure that the client removed the option $this->assertNull($config->get('client.resolvers')); }
/** * {@inheritdoc} */ public static function fromCommand(OperationCommand $command) { $data = $command->getResponse()->json(); // Collection of notifications if (self::isResponseDataIndexedArray($data)) { $notifications = new Collection(); foreach ($data as $key => $documentData) { $notifications->add($key, self::hydrateModelProperties(new self(), $documentData, array('applicationId' => 'referencingApplicationUuId'))); } return $notifications; } else { return self::hydrateModelProperties(new self(), $data, array('applicationId' => 'referencingApplicationUuId')); } }
/** * {@inheritdoc} */ public static function fromCommand(OperationCommand $command) { $data = $command->getResponse()->json(); // Indexed array of agent users if (self::isResponseDataIndexedArray($data)) { $users = new Collection(); foreach ($data as $key => $userData) { $users->add($key, self::hydrateModelProperties(new self(), $userData, array('agentUserId' => 'agentUserUuId', 'fullName' => 'name'))); } return $users; } else { return self::hydrateModelProperties(new self(), $data, array('agentUserId' => 'agentUserUuId', 'fullName' => 'name')); } }
/** * @param Parameter[] $parameters * @param Collection $collection */ public function addParameters(array $parameters, Collection $collection) { foreach ($parameters as $parameter) { $value = ''; $localParams = $parameter->getLocalParams(); if (!empty($localParams)) { if (!isset($localParameterSerializer)) { $localParameterSerializer = new LocalParameterSerializer(); } $value = $localParameterSerializer->serialize($localParams); } $value .= $parameter->getValue(); $collection->add($parameter->getKey(), $value); } }
/** * Gets Config Collection instance * * @param unknown $config * @return \Guzzle\Common\Collection */ public static function getConfigCollection($config) { $default = array('base_url' => 'http://manage.encoding.com'); $required = array('userid', 'userkey'); $config = Collection::fromConfig($config, $default, array('base_url', 'userid', 'userkey')); return $config; }
public static function factory($config = array(), $required = array()) { if (!defined('static::ENDPOINT')) { throw new Exception\ServiceEndpointException('A client must have an endpoint'); } $default = array('base_url' => '{scheme}://{domain}/' . static::ENDPOINT); $required = array_merge(array('scheme', 'domain', 'base_url'), $required); $config = Collection::fromConfig($config, $default, $required); $client = new static($config->get('base_url'), $config); $refClass = new \ReflectionClass(get_called_class()); $serviceDefinitionPath = dirname($refClass->getFileName()); $classNamePieces = explode('\\', get_called_class()); $serviceDefinitionFile = array_pop($classNamePieces) . '.json'; switch (true) { case is_readable(dirname($serviceDefinitionPath) . DIRECTORY_SEPARATOR . 'Resources' . DIRECTORY_SEPARATOR . $serviceDefinitionFile): $serviceDefinition = $serviceDefinitionPath . DIRECTORY_SEPARATOR . 'Resources' . DIRECTORY_SEPARATOR . $serviceDefinitionFile; break; case is_readable($serviceDefinitionPath . DIRECTORY_SEPARATOR . $serviceDefinitionFile): $serviceDefinition = $serviceDefinitionPath . DIRECTORY_SEPARATOR . $serviceDefinitionFile; break; default: throw new Exception\ClientConfigurationException('A client must have a service definition. Could not read the file "' . $serviceDefinition . '"'); } $description = ServiceDescription::factory($serviceDefinition); $client->setDescription($description); return $client; }
/** * @param array $config * @return \Guzzle\Service\Client|BasecampClient * @throws \Guzzle\Common\Exception\InvalidArgumentException */ public static function factory($config = array()) { $default = array('base_url' => 'https://basecamp.com/', 'version' => 'v1', 'token' => null, 'user_agent' => null, 'auth_method' => 'oauth'); $required = []; $config = Collection::fromConfig($config, $default, $required); $client = new self($config->get('base_url'), $config); if (empty($config['token'])) { throw new InvalidArgumentException("Config must contain token when using oath"); } $authorization = sprintf('Bearer %s', $config['token']); if (!isset($authorization)) { throw new InvalidArgumentException("Config must contain valid authentication method"); } // Attach a service description to the client $description = ServiceDescription::factory(__DIR__ . '/Resources/service.php'); $client->setDescription($description); // Set required User-Agent $client->setUserAgent($config['user_agent']); $client->getEventDispatcher()->addListener('request.before_send', function (Event $event) use($authorization) { $event['request']->addHeader('Authorization', $authorization); }); // Add cache plugin $cachePlugin = new CachePlugin(['storage' => new DefaultCacheStorage(new DoctrineCacheAdapter(new ApcCache()))]); $client->addSubscriber($cachePlugin); return $client; }
/** * @param array|Collection $parameters Collection of parameters to set on the command * @param OperationInterface $operation Command definition from description */ public function __construct($parameters = array(), OperationInterface $operation = null) { parent::__construct($parameters); $this->operation = $operation ?: $this->createOperation(); foreach ($this->operation->getParams() as $name => $arg) { $currentValue = $this[$name]; $configValue = $arg->getValue($currentValue); // If default or static values are set, then this should always be updated on the config object if ($currentValue !== $configValue) { $this[$name] = $configValue; } } $headers = $this[self::HEADERS_OPTION]; if (!$headers instanceof Collection) { $this[self::HEADERS_OPTION] = new Collection((array) $headers); } // You can set a command.on_complete option in your parameters to set an onComplete callback if ($onComplete = $this['command.on_complete']) { unset($this['command.on_complete']); $this->setOnComplete($onComplete); } // Set the hidden additional parameters if (!$this[self::HIDDEN_PARAMS]) { $this[self::HIDDEN_PARAMS] = array(self::HEADERS_OPTION, self::RESPONSE_PROCESSING, self::HIDDEN_PARAMS, self::REQUEST_OPTIONS); } $this->init(); }
/** * Create a collection of files to be migrated and add them to the read queue */ protected function enqueueGetRequests() { $files = $this->oldContainer->objectList(array('limit.total' => false, 'limit.page' => $this->options->get('read.pageLimit'))); foreach ($files as $file) { $this->readQueue->add($this->getClient()->get($file->getUrl())); } }
/** * @param array $config * @return \Guzzle\Service\Client|BasecampClient * @throws \Guzzle\Common\Exception\InvalidArgumentException */ public static function factory($config = array()) { $default = array('base_url' => 'https://basecamp.com/{user_id}/api/{version}/', 'version' => 'v1', 'auth' => 'http', 'token' => null, 'username' => null, 'password' => null); $required = array('user_id', 'app_name', 'app_contact'); $config = Collection::fromConfig($config, $default, $required); $client = new self($config->get('base_url'), $config); if ($config['auth'] === 'http') { if (!isset($config['username'], $config['password'])) { throw new InvalidArgumentException("Config must contain username and password when using http auth"); } $authorization = 'Basic ' . base64_encode($config['username'] . ':' . $config['password']); } if ($config['auth'] === 'oauth') { if (!isset($config['token'])) { throw new InvalidArgumentException("Config must contain token when using oauth"); } $authorization = sprintf('Bearer %s', $config['token']); } if (!isset($authorization)) { throw new InvalidArgumentException("Config must contain valid authentication method"); } // Attach a service description to the client $description = ServiceDescription::factory(__DIR__ . '/Resources/service.php'); $client->setDescription($description); // Set required User-Agent $client->setUserAgent(sprintf('%s (%s)', $config['app_name'], $config['app_contact'])); $client->getEventDispatcher()->addListener('request.before_send', function (Event $event) use($authorization) { $event['request']->addHeader('Authorization', $authorization); }); return $client; }
public static function factory($config = array()) { // The following values are required when creating the client $required = array('base_url', 'username', 'password'); // Merge in default settings and validate the config $config = Collection::fromConfig($config, array(), $required); // Create a new sData client $client = new self($config->get('base_url'), $config); // JSON by default $client->setDefaultOption('query/format', 'json'); // Authentication $client->setDefaultOption('auth', array($config->get('username'), $config->get('password'), 'Basic')); // Strip the BOM from results $client->addSubscriber(new StripBomPlugin()); // Optional logging if ($config->get('log')) { $client->getEventDispatcher()->addListener('request.before_send', function (Event $event) { $req = $event['request']; \Log::info('sData', ['request' => $req->getMethod() . ' ' . $req->getResource()]); }); } // Set the service description $services = \Config::get('sdata::services'); if (!empty($services)) { $client->setDescription(ServiceDescription::factory($services)); } // Done return $client; }
/** * @param array $config * @param string $configSection */ public function __construct($config, $configSection = null) { $this->endpoint = $this->getConfigurationItem($config, $configSection, "endpoint"); $this->username = $this->getConfigurationItem($config, $configSection, "username"); $this->password = $this->getConfigurationItem($config, $configSection, "password"); $this->guzzleConfig = Collection::fromConfig(array("base_url" => $this->endpoint, "username" => $this->username, "password" => $this->password)); }
public static function factory($config = array()) { if (isset($config['developer_mode']) && is_bool($config['developer_mode'])) { $developerMode = $config['developer_mode']; } else { $developerMode = false; } $baseUrl = array('https://api.auspost.com.au', 'https://devcentre.auspost.com.au/myapi'); // Ignore unnecessary user-specified configuration values if ($developerMode) { unset($config['email_address']); unset($config['password']); } unset($config['base_url']); $default = array('developer_mode' => $developerMode, 'base_url' => $baseUrl[$developerMode], 'email_address' => '*****@*****.**', 'password' => 'password'); $required = array('developer_mode', 'base_url', 'email_address', "password"); $config = Collection::fromConfig($config, $default, $required); $client = new self($config->get('base_url'), $config); $client->getConfig()->setPath('request.options/headers/Authorization', 'Basic ' . base64_encode($config->get('email_address') . ':' . $config->get('password'))); $client->setDescription(ServiceDescription::factory(__DIR__ . '/service.json')); $client->setSslVerification(false); $client->getEventDispatcher()->addListener('request.before_send', function (Event $event) { $request = $event['request']; $request->addCookie('OBBasicAuth', 'fromDialog'); }); return $client; }
/** * Processes the configuration passed to self::factory() * * @param array|Guzzle\Common\Collection $config * * @return Guzzle\Common\Collection */ public function processConfig($config) { $required = array('authentication'); $default = array('api_version' => 2, 'base_url' => 'https://{subdomain}.desk.com/api/v{api_version}/'); $baseUrl = $default['base_url']; if (isset($config['base_url'])) { $baseUrl = $config['base_url']; } // Subdomain is required, if the base URL is the default (not // set), or if it contains "{subdomain}" in it if (strpos($baseUrl, '{subdomain}') !== false) { $required[] = 'subdomain'; } // Authentication is required, either OAuth or Basic // If none specified, try to autodetect it if (!isset($config['authentication'])) { if (isset($config['username']) && isset($config['password'])) { // If username and password are set, use basic auth $config['authentication'] = 'basic'; } elseif (isset($config['consumer_key']) && isset($config['consumer_secret']) && isset($config['token']) && isset($config['token_secret'])) { // Otherwise, use OAuth if we have enough data $config['authentication'] = 'oauth'; } } return Collection::fromConfig($config, $default, $required); }
public static function factory($config = array()) { // provide a hash of default client configuration options $default = array('base_url' => 'http://127.0.0.1/', 'api_id' => 1, 'private_key' => 'fbdce19f94b158e72ae6020cc5126642a9d42d086419c015ad2b6dd429312410'); // the following values are required when creating the client $required = array('base_url', 'api_id', 'private_key'); // merge in default settings and validate the config $config = \Guzzle\Common\Collection::fromConfig($config, $default, $required); // create a new client $client = new self($config->get('base_url'), $config); $client->setDefaultOption('headers/API_ID', $config->get('api_id')); $client->getEventDispatcher()->addListener('client.create_request', function (\Guzzle\Common\Event $event) use($config) { // Guzzle\Http\Message\Request $data = $event['request']->getQuery(); // Guzzle\Http\Message\EntityEnclosingRequest if ($event['request'] instanceof Guzzle\Http\Message\EntityEnclosingRequest) { $data->overwriteWith($event['request']->getPostFields()); } $time = (string) time(); $message = $time . $config->get('api_id') . implode($data->toArray()); $hash = hash_hmac('sha256', $message, $config->get('private_key')); $event['request']->setHeader('API_TIME', $time)->setHeader('API_HASH', $hash); unset($data, $time, $message, $hash); }); return $client; }
/** * {@inheritdoc} */ public static function factory($config = array()) { $default = array('url' => false, 'munchkin_id' => false, 'version' => 1, 'bulk' => false); $required = array('client_id', 'client_secret', 'version'); $config = Collection::fromConfig($config, $default, $required); $url = $config->get('url'); if (!$url) { $munchkin = $config->get('munchkin_id'); if (!$munchkin) { throw new \Exception('Must provide either a URL or Munchkin code.'); } $url = sprintf('https://%s.mktorest.com', $munchkin); } $grantType = new Credentials($url, $config->get('client_id'), $config->get('client_secret')); $auth = new Oauth2Plugin($grantType); if ($config->get('bulk') === true) { $restUrl = sprintf('%s/bulk/v%d', rtrim($url, '/'), $config->get('version')); } else { $restUrl = sprintf('%s/rest/v%d', rtrim($url, '/'), $config->get('version')); } $client = new self($restUrl, $config); $client->addSubscriber($auth); $client->setDescription(ServiceDescription::factory(__DIR__ . '/service.json')); $client->setDefaultOption('headers/Content-Type', 'application/json'); return $client; }