作者:MicroSDH
项目:justinribeiro.com-example
/**
* 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;
}
作者:romainneutro
项目:aws-sdk-ph
/**
* @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();
}
作者:NavalKisho
项目:PHP-Rocke
/**
* @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;
}
作者:AlexEvesDevelope
项目:hl-stuf
/**
* {@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;
}
作者:noahki
项目:kowo
/**
* 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));
}
作者:ja1ca
项目:GoogleTranslateBundl
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);
}
作者:risyasi
项目:webpagetes
/**
* 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()));
}
作者:AlexEvesDevelope
项目:hl-stuf
/**
* {@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;
}
作者:MicroSDH
项目:justinribeiro.com-example
/**
* 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());
}
作者:jsnshrm
项目:Sum
/**
* 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;
}
作者:AlexEvesDevelope
项目:hl-stuf
/**
* {@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);
}
}
作者:noahki
项目:kowo
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'));
}
作者:AlexEvesDevelope
项目:hl-stuf
/**
* {@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'));
}
}
作者:AlexEvesDevelope
项目:hl-stuf
/**
* {@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'));
}
}
作者:cultuurne
项目:searc
/**
* @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);
}
}
作者:svilbor
项目:guzzle-encoding-co
/**
* 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;
}
作者:fancygu
项目:guzzle-clien
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;
}
作者:bigset
项目:blueridg
/**
* @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;
}
作者:omusic
项目:isle-web-framewor
/**
* @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();
}
作者:netvlie
项目:basecamp-ph
/**
* @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;
}