Пример #1
0
 public function testGetsValuesByKey()
 {
     $this->assertNull($this->coll->get('test'));
     $this->coll->add('test', 'value');
     $this->assertEquals('value', $this->coll->get('test'));
     $this->coll->set('test2', 'v2');
     $this->coll->set('test3', 'v3');
     $this->assertEquals(array('test' => 'value', 'test2' => 'v2'), $this->coll->getAll(array('test', 'test2')));
 }
Пример #2
0
 /**
  * @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];
 }
 public function setConfig(array $clientConfig)
 {
     if (array_key_exists('curl', $clientConfig)) {
         $curl = $clientConfig['curl'];
         unset($clientConfig['curl']);
     }
     $this->config = new Collection($clientConfig);
     if (is_array($curl)) {
         $this->config->set(Client::CURL_OPTIONS, $curl);
     }
     return $this;
 }
Пример #4
0
 /**
  * @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();
 }
Пример #5
0
 /**
  * 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;
 }
Пример #6
0
 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'));
 }
Пример #7
0
 /**
  * Called when a request is being retried
  *
  * @param Event $event Event emitted
  */
 public function onRequestRetry(Event $event)
 {
     $request = $event['request'];
     $response = $event['response'];
     $handle = $event['handle'];
     $data = new Collection(array('ts' => gmdate('c'), 'method' => $request->getMethod(), 'url' => $request->getUrl(), 'retries' => $event['retries'], 'delay' => $event['delay']));
     if ($response) {
         $data->merge(array('code' => $response->getStatusCode(), 'phrase' => $response->getReasonPhrase(), 'connect_time' => $response->getInfo('connect_time'), 'total_time' => $response->getInfo('total_time')));
     }
     if ($handle) {
         $data->set('curl_error', $handle->getError());
         $data->set('curl_code', $handle->getErrorNo());
     }
     // Add request headers to the possible template values
     foreach ($request->getHeaders(true) as $header => $value) {
         $data->set("header_{$header}", (string) $value);
     }
     $this->logger->log($data->inject($this->template), LOG_INFO, $data);
 }
Пример #8
0
 private function handleEndpoint(Collection $config)
 {
     // Alias "endpoint" with "base_url" for forwards compatibility.
     if ($config['endpoint']) {
         $config[Options::BASE_URL] = $config['endpoint'];
         return;
     }
     if ($config[Options::BASE_URL]) {
         return;
     }
     $endpoint = call_user_func($config['endpoint_provider'], array('scheme' => $config[Options::SCHEME], 'region' => $config[Options::REGION], 'service' => $config[Options::SERVICE]));
     $config[Options::BASE_URL] = $endpoint['endpoint'];
     // Set a signature if one was not explicitly provided.
     if (!$config->hasKey(Options::SIGNATURE) && isset($endpoint['signatureVersion'])) {
         $config->set(Options::SIGNATURE, $endpoint['signatureVersion']);
     }
     // The the signing region if endpoint rule specifies one.
     if (isset($endpoint['credentialScope'])) {
         $scope = $endpoint['credentialScope'];
         if (isset($scope['region'])) {
             $config->set(Options::SIGNATURE_REGION, $scope['region']);
         }
     }
 }
Пример #9
0
 /**
  * Update a configuration object from a service description
  *
  * @param Collection $config Config to update
  *
  * @return ServiceDescription
  * @throws InvalidArgumentException
  */
 protected function updateConfigFromDescription(Collection $config)
 {
     $description = $config->get(Options::SERVICE_DESCRIPTION);
     if (!$description instanceof ServiceDescription) {
         // Inject the version into the sprintf template if it is a string
         if (is_string($description)) {
             $description = sprintf($description, $config->get(Options::VERSION));
         }
         $description = ServiceDescription::factory($description);
         $config->set(Options::SERVICE_DESCRIPTION, $description);
     }
     if (!$config->get(Options::SERVICE)) {
         $config->set(Options::SERVICE, $description->getData('endpointPrefix'));
     }
     if ($iterators = $description->getData('iterators')) {
         $this->setIteratorsConfig($iterators);
     }
     // Ensure that the service description has regions
     if (!$description->getData('regions')) {
         throw new InvalidArgumentException('No regions found in the ' . $description->getData('serviceFullName') . ' description');
     }
     // Make sure a valid region is set
     $region = $config->get(Options::REGION);
     $global = $description->getData('globalEndpoint');
     if (!$global && !$region) {
         throw new InvalidArgumentException('A region is required when using ' . $description->getData('serviceFullName') . '. Set "region" to one of: ' . implode(', ', array_keys($description->getData('regions'))));
     } elseif ($global && (!$region || $description->getData('namespace') !== 'S3')) {
         $region = Region::US_EAST_1;
         $config->set(Options::REGION, $region);
     }
     if (!$config->get(Options::BASE_URL)) {
         // Set the base URL using the scheme and hostname of the service's region
         $config->set(Options::BASE_URL, AbstractClient::getEndpoint($description, $region, $config->get(Options::SCHEME)));
     }
     return $description;
 }
Пример #10
0
 /**
  * Update a configuration object from a service description
  *
  * @param Collection $config Config to update
  *
  * @return ServiceDescription
  * @throws InvalidArgumentException
  */
 protected function updateConfigFromDescription(Collection $config)
 {
     $description = $config->get(Options::SERVICE_DESCRIPTION);
     if (!$description instanceof ServiceDescription) {
         // Inject the version into the sprintf template if it is a string
         if (is_string($description)) {
             $description = sprintf($description, $config->get(Options::VERSION));
         }
         $description = ServiceDescription::factory($description);
         $config->set(Options::SERVICE_DESCRIPTION, $description);
     }
     if (!$config->get(Options::SERVICE)) {
         $config->set(Options::SERVICE, $description->getData('endpointPrefix'));
     }
     if ($iterators = $description->getData('iterators')) {
         $this->setIteratorsConfig($iterators);
     }
     // Make sure a valid region is set
     $region = $config->get(Options::REGION);
     $global = $description->getData('globalEndpoint');
     if (!$global && !$region) {
         throw new InvalidArgumentException('A region is required when using ' . $description->getData('serviceFullName'));
     } elseif ($global && (!$region || $description->getData('namespace') !== 'S3')) {
         $region = 'us-east-1';
         $config->set(Options::REGION, 'us-east-1');
     }
     if (!$config->get(Options::BASE_URL)) {
         $endpoint = call_user_func($config->get('endpoint_provider'), array('scheme' => $config->get(Options::SCHEME), 'region' => $region, 'service' => $config->get(Options::SERVICE)));
         $config->set(Options::BASE_URL, $endpoint['endpoint']);
         // Set a signature if one was not explicitly provided.
         if (!$config->hasKey(Options::SIGNATURE) && isset($endpoint['signatureVersion'])) {
             $config->set(Options::SIGNATURE, $endpoint['signatureVersion']);
         }
     }
     return $description;
 }
Пример #11
0
 /**
  * @deprecated Use $message->getHeader()->parseParams()
  * @codeCoverageIgnore
  */
 public function getTokenizedHeader($header, $token = ';')
 {
     Version::warn(__METHOD__ . ' is deprecated. Use $message->getHeader()->parseParams()');
     if ($this->hasHeader($header)) {
         $data = new Collection();
         foreach ($this->getHeader($header)->parseParams() as $values) {
             foreach ($values as $key => $value) {
                 if ($value === '') {
                     $data->set($data->count(), $key);
                 } else {
                     $data->add($key, $value);
                 }
             }
         }
         return $data;
     }
 }
Пример #12
0
 /**
  * Update a configuration object from a service description
  *
  * @param Collection $config Config to update
  *
  * @return ServiceDescription
  * @throws InvalidArgumentException
  */
 protected function updateConfigFromDescription(Collection $config)
 {
     $description = $config->get(Options::SERVICE_DESCRIPTION);
     if (!$description instanceof ServiceDescription) {
         $description = ServiceDescription::factory($description);
         $config->set(Options::SERVICE_DESCRIPTION, $description);
     }
     if (!$config->get(Options::SERVICE)) {
         $config->set(Options::SERVICE, $description->getData('endpointPrefix'));
     }
     if ($iterators = $description->getData('iterators')) {
         $this->setIteratorsConfig($iterators);
     }
     // Ensure that the service description has regions
     if (!$description->getData('regions')) {
         throw new InvalidArgumentException('No regions found in the ' . $description->getData('serviceFullName') . ' description');
     }
     $region = $config->get(Options::REGION);
     if (!$region) {
         if (!$description->getData('globalEndpoint')) {
             throw new InvalidArgumentException('A region is required when using ' . $description->getData('serviceFullName') . '. Set "region" to one of: ' . implode(', ', array_keys($description->getData('regions'))));
         }
         $region = 'us-east-1';
         $config->set(Options::REGION, $region);
     }
     if (!$config->get(Options::BASE_URL)) {
         // Set the base URL using the scheme and hostname of the service's region
         $config->set(Options::BASE_URL, AbstractClient::getEndpoint($description, $region, $config->get(Options::SCHEME)));
     }
     return $description;
 }
Пример #13
0
 /**
  * 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);
 }
Пример #14
0
 /**
  * {@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;
     }
 }
Пример #15
0
 /**
  * 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)));
 }
Пример #16
0
 /**
  * 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   Set to FALSE to allow missing required fields
  * @param bool       $validate 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 ($configValue && is_string($configValue)) {
             $configValue = $config->inject($configValue);
         }
         // 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[] = $name . ': ' . $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.';
             }
         }
     }
     if (empty($errors)) {
         return true;
     } elseif ($strict) {
         throw new ValidationException('Validation errors: ' . implode("\n", $errors));
     }
     return $errors;
 }