/** * 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); }
/** * 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)); }
/** * @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())); }
/** * 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())); } }
/** * Retrieve access token * * @param Collection $config * * @return string */ protected static function retrieveAccessToken(Collection $config) { $client = new \Guzzle\Http\Client($config->get('oauth2_token')); $request = $client->get(); $query = $request->getQuery(); $query->set('grant_type', $config->get('grant_type')); $query->set('client_id', $config->get('client_id')); $query->set('client_secret', $config->get('client_secret')); $query->set('api_key', $config->get('api_key')); try { $response = $request->send(); $json = $response->json(); } catch (\Guzzle\Http\Exception\BadResponseException $ex) { throw new \Exception('Bad authentification, please check your oauth settings'); } return $json['access_token']; }
/** * @covers Guzzle\Common\Collection::offsetGet * @covers Guzzle\Common\Collection::offsetSet * @covers Guzzle\Common\Collection::offsetUnset * @covers Guzzle\Common\Collection::offsetExists */ public function testImplementsArrayAccess() { $this->coll->merge(array('k1' => 'v1', 'k2' => 'v2')); $this->assertTrue($this->coll->offsetExists('k1')); $this->assertFalse($this->coll->offsetExists('Krull')); $this->coll->offsetSet('k3', 'v3'); $this->assertEquals('v3', $this->coll->offsetGet('k3')); $this->assertEquals('v3', $this->coll->get('k3')); $this->coll->offsetUnset('k1'); $this->assertFalse($this->coll->offsetExists('k1')); }
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 function resolve(Collection $config, AwsClientInterface $client = null) { // A user can inject the plugin in their options array or have one // created for them by default $plugin = $config->get(Options::BACKOFF); if (!$plugin && $this->missingFunction) { $plugin = call_user_func($this->missingFunction, $config, $client); $config->set(Options::BACKOFF, $plugin); // The log option can be set to `debug` or an instance of a LogAdapterInterface if ($logger = $config->get(Options::BACKOFF_LOGGER)) { $this->addLogger($plugin, $logger, $config->get(Options::BACKOFF_LOGGER_TEMPLATE)); } } // Ensure that the plugin implements the correct interface if ($plugin && !$plugin instanceof BackoffPlugin) { throw new InvalidArgumentException(Options::BACKOFF . ' must be an instance of Guzzle\\Plugin\\Backoff\\BackoffPlugin'); } // Attach the BackoffPlugin to the client if ($client) { $client->addSubscriber($plugin, -255); } }
/** * {@inheritdoc} */ public function resolve(Collection $config, AwsClientInterface $client = null) { $signature = $config->get(Options::SIGNATURE); // Ensure that a signature object is passed to the client if (!$signature && $this->missingFunction) { // The signature was not provided, so use the callback to get one $signature = call_user_func($this->missingFunction, $config); $config->set(Options::SIGNATURE, $signature); } elseif (!$signature instanceof $this->mustImplement) { throw new InvalidArgumentException('An explicitly provided ' . Options::SIGNATURE . ' option must implement SignatureInterface'); } // If this is a region and service specific signature object then add // these values to the signature object if they are present in the config if ($signature instanceof EndpointSignatureInterface) { if ($serviceName = $config->get(Options::SIGNATURE_SERVICE)) { $signature->setServiceName($serviceName); } if ($regionName = $config->get(Options::SIGNATURE_REGION)) { $signature->setRegionName($regionName); } } }
/** * @dataProvider falseyDataProvider */ public function testReturnsCorrectData($a, $b) { $c = new Collection(array('value' => $a)); $this->assertSame($b, $c->get('value')); }
/** * Return an appropriate signature object for a a client based on a description * * @param ServiceDescription $description Description that holds a signature option * @param Collection $config Configuration options * * @throws InvalidArgumentException */ protected function addSignature(ServiceDescription $description, Collection $config) { if (!($signature = $config->get(Options::SIGNATURE))) { if (!$description->getData('signatureVersion')) { throw new InvalidArgumentException('The service description does not specify a signatureVersion'); } switch ($description->getData('signatureVersion')) { case 'v2': $signature = new SignatureV2(); break; case 'v3': $signature = new SignatureV3(); break; case 'v3https': $signature = new SignatureV3Https(); break; case 'v4': $signature = new SignatureV4(); break; } } // Allow a custom service name or region value to be provided if ($signature instanceof EndpointSignatureInterface) { $signature->setServiceName($config->get(Options::SIGNATURE_SERVICE) ?: $description->getData('signingName')); $signature->setRegionName($config->get(Options::SIGNATURE_REGION)); } $config->set(Options::SIGNATURE, $signature); }
/** * Add a base URL to the client of a region, scheme, and service were provided instead * * @param Collection $config Config object * * @throws InvalidArgumentException if required parameters are not set */ protected function addBaseUrlToConfig(Collection $config) { $region = $config->get(Options::REGION); $service = $config->get(Options::SERVICE); if (!$region || !$service) { throw new InvalidArgumentException('You must specify a [base_url] or a [region, service, and optional scheme]'); } $endpoint = $config->get(Options::ENDPOINT_PROVIDER)->getEndpoint($service, $region); $config->set(Options::BASE_URL, $endpoint->getBaseUrl($config->get(Options::SCHEME))); }
/** * {@inheritdoc} * @throws ValidationException when validation errors occur */ public function validate(Collection $config, Inspector $inspector = null) { $inspector = $inspector ?: Inspector::getInstance(); $typeValidation = $inspector->getTypeValidation(); $errors = array(); foreach ($this->params as $name => $arg) { $currentValue = $config->get($name); $configValue = $arg->getValue($currentValue); // Inject configuration information into the config value if ($configValue && is_string($configValue)) { $configValue = $config->inject($configValue); } // Ensure that required arguments are set if ($arg->getRequired() && ($configValue === null || $configValue === '')) { $errors[] = 'Requires that the ' . $name . ' argument be supplied.' . ($arg->getDoc() ? ' (' . $arg->getDoc() . ').' : ''); continue; } // Ensure that the correct data type is being used if ($typeValidation && $configValue !== null && ($argType = $arg->getType())) { $validation = $inspector->validateConstraint($argType, $configValue, $arg->getTypeArgs()); if ($validation !== true) { $errors[] = $name . ': ' . $validation; $config->set($name, $configValue); continue; } } $configValue = $arg->filter($configValue); // Update the config value if it changed if (!$configValue !== $currentValue) { $config->set($name, $configValue); } // Check the length values if validating data $argMinLength = $arg->getMinLength(); if ($argMinLength && strlen($configValue) < $argMinLength) { $errors[] = 'Requires that the ' . $name . ' argument be >= ' . $arg->getMinLength() . ' characters.'; } $argMaxLength = $arg->getMaxLength(); if ($argMaxLength && strlen($configValue) > $argMaxLength) { $errors[] = 'Requires that the ' . $name . ' argument be <= ' . $arg->getMaxLength() . ' characters.'; } } if (!empty($errors)) { $e = new ValidationException('Validation errors: ' . implode("\n", $errors)); $e->setErrors($errors); throw $e; } }
/** * Return an appropriate signature object for a a client based on a description * * @param ServiceDescription $description Description that holds a signature option * @param Collection $config Configuration options * * @return SignatureInterface * @throws InvalidArgumentException */ protected function getSignature(ServiceDescription $description, Collection $config) { if (!($signature = $config->get(Options::SIGNATURE))) { switch ($description->getData('signatureVersion')) { case 'v2': $signature = new SignatureV2(); break; case 'v3': $signature = new SignatureV3(); break; case 'v3https': $signature = new SignatureV3Https(); break; case 'v4': $signature = new SignatureV4(); break; default: throw new InvalidArgumentException('Service description does not specify a valid signatureVersion'); } } // Allow a custom service name or region value to be provided if ($signature instanceof EndpointSignatureInterface) { // Determine the service name to use when signing if (!($service = $config->get(Options::SIGNATURE_SERVICE))) { if (!($service = $description->getData('signingName'))) { $service = $description->getData('endpointPrefix'); } } $signature->setServiceName($service); // Determine the region to use when signing requests if (!($region = $config->get(Options::SIGNATURE_REGION))) { $region = $config->get(Options::REGION); } $signature->setRegionName($region); } return $signature; }
/** * Configures the client by setting the appropriate headers, service description and error handling * * @param Collection $config */ protected function configure($config) { $this->setDefaultOption('headers', $config->get('headers')); $this->setDescription($this->getServiceDescriptionFromFile($config->get('service_description'))); $this->setErrorHandler(); }
/** * Return an appropriate signature object for a a client based on the * "signature" configuration setting, or the default signature specified in * a service description. The signature can be set to a valid signature * version identifier string or an instance of Aws\Common\Signature\SignatureInterface. * * @param ServiceDescription $description Description that holds a signature option * @param Collection $config Configuration options * * @return SignatureInterface * @throws InvalidArgumentException */ protected function getSignature(ServiceDescription $description, Collection $config) { // If a custom signature has not been provided, then use the default // signature setting specified in the service description. $signature = $config->get(Options::SIGNATURE) ?: $description->getData('signatureVersion'); if (is_string($signature)) { if ($signature == 'v4') { $signature = new SignatureV4(); } elseif ($signature == 'v2') { $signature = new SignatureV2(); } elseif ($signature == 'v3https') { $signature = new SignatureV3Https(); } else { throw new InvalidArgumentException("Invalid signature type: {$signature}"); } } elseif (!$signature instanceof SignatureInterface) { throw new InvalidArgumentException('The provided signature is not ' . 'a signature version string or an instance of ' . 'Aws\\Common\\Signature\\SignatureInterface'); } // Allow a custom service name or region value to be provided if ($signature instanceof EndpointSignatureInterface) { // Determine the service name to use when signing $signature->setServiceName($config->get(Options::SIGNATURE_SERVICE) ?: $description->getData('signingName') ?: $description->getData('endpointPrefix')); // Determine the region to use when signing requests $signature->setRegionName($config->get(Options::SIGNATURE_REGION) ?: $config->get(Options::REGION)); } return $signature; }
protected function getCredentials(Collection $config) { $credentials = $config->get(Options::CREDENTIALS); if (is_array($credentials)) { $credentials = Credentials::factory($credentials); } elseif ($credentials === false) { $credentials = new NullCredentials(); } elseif (!$credentials instanceof CredentialsInterface) { $credentials = Credentials::factory($config); } return $credentials; }
/** * Validates that all required args are included in a config object, * and if not, throws an InvalidArgumentException with a helpful error message. Adds * default args to the passed config object if the parameter was not * set in the config object. * * @param array $params Params to validate * @param Collection $config Configuration settings * @param bool $strict (optional) Set to FALSE to allow missing required fields * @param bool $validate (optional) Set to TRUE or FALSE to validate data. * Set to false when you only need to add default values and statics. * * @return array|bool Returns an array of errors or TRUE on success * * @throws InvalidArgumentException if any args are missing and $strict is TRUE */ public function validateConfig(array $params, Collection $config, $strict = true, $validate = true) { $errors = array(); foreach ($params as $name => $arg) { // Set the default or static value if it is not set $configValue = $arg->getValue($config->get($name)); // Inject configuration information into the config value if (is_string($configValue)) { $configValue = Guzzle::inject($configValue, $config); } // Ensure that required arguments are set if ($validate && $arg->getRequired() && ($configValue === null || $configValue === '')) { $errors[] = 'Requires that the ' . $name . ' argument be supplied.' . ($arg->getDoc() ? ' (' . $arg->getDoc() . ').' : ''); continue; } // Ensure that the correct data type is being used if ($validate && $this->typeValidation && $configValue !== null && ($argType = $arg->getType())) { $validation = $this->validateConstraint($argType, $configValue); if ($validation !== true) { $errors[] = $validation; continue; } } // Run the value through attached filters $configValue = $arg->filter($configValue); $config->set($name, $configValue); // Check the length values if validating data if ($validate) { $argMinLength = $arg->getMinLength(); if ($argMinLength && strlen($configValue) < $argMinLength) { $errors[] = 'Requires that the ' . $name . ' argument be >= ' . $arg->getMinLength() . ' characters.'; } $argMaxLength = $arg->getMaxLength(); if ($argMaxLength && strlen($configValue) > $argMaxLength) { $errors[] = 'Requires that the ' . $name . ' argument be <= ' . $arg->getMaxLength() . ' characters.'; } } $config->set($name, $configValue); } if (empty($errors)) { return true; } else { if ($strict) { throw new ValidationException('Validation errors: ' . implode("\n", $errors)); } } return $errors; }