public function __construct(ClientInterface $client = null, $config = null) { $this->client = $client; if ($config) { $this->config = Collection::fromConfig($config, ['grant_type' => 'client_credentials', 'client_secret' => '', 'scope' => ''], ['client_id']); } }
public static function factory($options = array()) { $defaultOptions = array('base_url' => self::getDefaultServiceUrl(), 'defaults' => array('exceptions' => false, 'connect_timeout' => 10, 'timeout' => 60)); // $requiredOptions = array(); // // foreach ($requiredOptions as $optionName) { // if (!isset($options[$optionName]) || $options[$optionName] === '') { // throw new Exception\InvalidArgumentException( // sprintf('Missing required configuration option "%s"', $optionName) // ); // } // } $config = Collection::fromConfig($options, $defaultOptions); $headers = array('Accept' => 'application/json', 'User-Agent' => 'denner-client/' . self::CLIENT_VERSION); if (isset($options['app_id'])) { $headers['App-ID'] = $options['app_id']; } if (isset($options['app_key'])) { $headers['App-Key'] = $options['app_key']; } $httpClient = new HttpClient($config->toArray()); $httpClient->setDefaultOption('headers', $headers); $httpClient->getEmitter()->attach(new Subscriber\ErrorHandler()); $serviceDescriptionFile = __DIR__ . sprintf('/ServiceDescription/%s.php', self::getServiceDescriptionName()); if (!file_exists($serviceDescriptionFile)) { throw new Exception\RuntimeException(sprintf('Service description does not exist at "%s"', $serviceDescriptionFile)); } $description = new ServiceDescription(require $serviceDescriptionFile); $client = new static($httpClient, $description); return $client; }
public static function factory($options = array()) { $defaultOptions = array('base_url' => 'https://lw-inside.detailnet.ch/api/', 'defaults' => array('exceptions' => false, 'connect_timeout' => 10, 'timeout' => 60)); // $requiredOptions = array(); // // foreach ($requiredOptions as $optionName) { // if (!isset($options[$optionName]) || $options[$optionName] === '') { // throw new Exception\InvalidArgumentException( // sprintf('Missing required configuration option "%s"', $optionName) // ); // } // } $config = Collection::fromConfig($options, $defaultOptions); $headers = array('Accept' => 'application/json', 'User-Agent' => 'lw-inside-client/' . self::CLIENT_VERSION); if (isset($options['app_id'])) { $headers['App-ID'] = $options['app_id']; } if (isset($options['app_key'])) { $headers['App-Key'] = $options['app_key']; } $httpClient = new HttpClient($config->toArray()); $httpClient->setDefaultOption('headers', $headers); $httpClient->getEmitter()->attach(new Subscriber\ErrorHandler()); $description = new ServiceDescription(require __DIR__ . '/ServiceDescription/Inside.php'); $client = new self($httpClient, $description); return $client; }
public function __construct(ClientInterface $client = null, $config = null) { $this->client = $client; if ($config) { $this->config = Collection::fromConfig($config, ['client_secret' => '', 'refresh_token' => '', 'scope' => ''], ['client_id']); } }
/** * Create a OVH subscriber * * @param array $config Configuration array containing these parameters: * - string version */ public function __construct($config) { $this->config = Collection::fromConfig($config, array('application_key' => 'anonymous', 'application_secret' => 'anonymous', 'consumer_key' => 'anonymous'), array('application_key', 'application_secret', 'consumer_key')); $this->applicationKey = $this->config['application_key']; $this->applicationSecret = $this->config['application_secret']; $this->consumerKey = $this->config['consumer_key']; }
public function __construct(ClientInterface $client = null, $config = null) { $this->client = $client; if ($config) { $this->config = Collection::fromConfig($config, ['client_secret' => '', 'scope' => ''], ['client_id', 'username', 'password']); } }
/** * Creates a new AuthTokenFetcher plugin. * * @param FetchAuthTokenInterface $fetcher is used to fetch the auth token * @param array $cacheConfig configures the cache * @param CacheInterface $cache (optional) caches the token. */ public function __construct(FetchAuthTokenInterface $fetcher, array $cacheConfig = null, CacheInterface $cache = null) { $this->fetcher = $fetcher; if (!is_null($cache)) { $this->cache = $cache; $this->cacheConfig = Collection::fromConfig($cacheConfig, ['lifetime' => self::DEFAULT_CACHE_LIFETIME, 'prefix' => ''], []); } }
/** * Create a new ViewRangerClient * * @param string $apiKey * @param array $config * * @return ViewRangerClientInterface * @throws \Exception */ public static function create($apiKey, $config = []) { $defaults = ['base_url' => 'https://api.viewranger.com/public/v1', 'defaults' => ['query' => ['format' => 'json', 'key' => $apiKey], 'headers' => ['User-Agent' => 'ViewRangerClient']]]; $config = Collection::fromConfig($config, $defaults, []); $config = $config->toArray(); $client = new Client($config); return new static($client, new ViewRangerDescription()); }
public function __construct(Config $config) { $defaultOptions = ['scheme' => 'http']; $requiredOptions = ['hostname']; $options = ['hostname' => $config->getHostname(), 'scheme' => $config->getUseSsl() ? 'https' : 'http', 'port' => $config->getPort()]; $options = Collection::fromConfig($options, $defaultOptions, $requiredOptions); $this->client = new Client(['base_url' => ['{scheme}://{hostname}:{port}/api/', $options->toArray()], 'defaults' => ['auth' => [$config->getLogin(), $config->getPassword()], 'expect' => false, 'headers' => ['Accept' => 'application/json', 'User-Agent' => 'Openl10n ' . Client::getDefaultUserAgent()]]]); $this->registerDefaultEntryPoints(); }
public function __construct(Config $config) { $defaultOptions = ['scheme' => 'https', 'version' => 'v1']; $requiredOptions = ['hostname']; $options = ['hostname' => $config->getHostname(), 'scheme' => $config->getUseSsl() ? 'https' : 'http', 'port' => $config->getPort(), 'version' => $config->getVersion()]; $options = Collection::fromConfig($options, $defaultOptions, $requiredOptions); $this->client = new Client(['base_url' => ['{scheme}://{hostname}:{port}/api/{version}/', $options->toArray()], 'defaults' => ['headers' => ['Content-Type' => 'application/json'], 'auth' => [$config->getLogin(), $config->getPassword()]]]); $this->registerDefaultEntryPoints(); }
/** * Creates a Message object from an array of raw message data * * @param array $data The message data * * @return Message * @throws \InvalidArgumentException If a valid type is not provided or there are other required keys missing */ public static function fromArray(array $data) { // Make sure the type key is set if (!isset($data['Type'])) { throw new \InvalidArgumentException('The "Type" key must be ' . 'provided to instantiate a Message object.'); } // Determine required keys and create a collection from the message data $requiredKeys = array_merge(self::$requiredKeys['__default'], isset(self::$requiredKeys[$data['Type']]) ? self::$requiredKeys[$data['Type']] : []); $data = Collection::fromConfig($data, [], $requiredKeys); return new self($data); }
/** * Creates a new ScopedAccessToken plugin. * * @param object $tokenFunc a token generator function * @param array|string scopes the token authentication scopes * @param cacheConfig configuration for the cache when it's present * @param object $cache an implementation of CacheInterface */ public function __construct(callable $tokenFunc, $scopes, array $cacheConfig, CacheInterface $cache = NULL) { $this->tokenFunc = $tokenFunc; if (!(is_string($scopes) || is_array($scopes))) { throw new \InvalidArgumentException('wants scope should be string or array'); } $this->scopes = $scopes; if (!is_null($cache)) { $this->cache = $cache; $this->cacheConfig = Collection::fromConfig($cacheConfig, ['lifetime' => self::DEFAULT_CACHE_LIFETIME, 'prefix' => ''], []); } }
/** * Instantiates a new SyneriseTracker instance. * @param array $config */ public function __construct($config = array()) { if (isset($config['allowFork']) && $config['allowFork'] == true) { $config['handler'] = new ForkCurlHandler([]); } parent::__construct($config); $this->client = Producers\Client::getInstance(); $this->event = Event::getInstance(); $this->transaction = Producers\Transaction::getInstance(); $config = Collection::fromConfig($config, static::getDefaultConfig(), static::$required); $this->configure($config); }
/** * @param array $config * Possible configuration keys are: * - accounts (string): The endpoint URL for the accounts API. * - client_id (string): The OAuth2 client ID for this client. * - debug (bool): Whether or not Guzzle debugging should be enabled * (default: false). * - verify (bool): Whether or not SSL verification should be enabled * (default: true). * - user_agent (string): The HTTP User-Agent for API requests. * - cache (array|bool): Caching. Set to true to enable in-memory * caching, to false (the default) to disable caching, or to an array * of options as expected by the Guzzle cache subscriber. * - proxy (array|string): A proxy setting, passed to Guzzle directly. * Use a string to specify an HTTP proxy, or an array to specify * different proxies for different protocols. * @param SessionInterface $session */ public function __construct(array $config = [], SessionInterface $session = null) { $version = '0.1.x'; $url = 'https://github.com/platformsh/platformsh-client-php'; $defaults = ['accounts' => 'https://marketplace.commerceguys.com/api/platform/', 'client_id' => 'platformsh-client-php', 'client_secret' => '', 'debug' => false, 'verify' => true, 'user_agent' => "Platform.sh-Client-PHP/{$version} (+{$url})", 'cache' => false, 'token_url' => '/oauth2/token', 'proxy' => null]; $this->config = Collection::fromConfig($config, $defaults); $this->session = $session ?: new Session(); if (isset($this->config['api_token'])) { $this->setApiToken($this->config['api_token']); unset($this->config['api_token']); } }
/** * Create a new instance of GitlabClient. * @param array $config * @return GitlabGuzzleClient */ public static function createClient($config = []) { $default = ['ssl.certificate_authority' => 'system']; $required = ['base_url', 'api_token']; $config = Collection::fromConfig($config, $default, $required); $config['base_url'] = self::completeBaseUrl($config['base_url']); $serviceDescriptionFilePath = __DIR__ . '/ServiceDescription/service_description.yml'; $definition = self::loadServiceDefinition($serviceDescriptionFilePath); self::emulateGuzzle3ResponseModels($definition); $description = new Description($definition); $client = new Client($config->toArray()); $client->setDefaultOption('headers/accept', 'application/json'); $privateTokenPlugin = new PrivateTokenPlugin($config['api_token']); $client->getEmitter()->attach($privateTokenPlugin); $gitlabClient = new GitlabGuzzleClient($client, $description); $gitlabClient->getEmitter()->attach(new ResponseClassProcessor($description)); return $gitlabClient; }
/** * Prepares the POST object to be utilzed to build a POST form. * * @return PostObject */ public function prepareData() { // Validate required options $options = Collection::fromConfig($this->data, ['ttd' => '+1 hour', 'key' => '^${filename}']); $ttd = $this->pluckTtd($options); // If a policy or policy callback were provided, extract those from // the options. $rawJsonPolicy = $options['policy']; $policyCallback = $options['policy_callback']; unset($options['policy'], $options['policy_callback']); // Setup policy document $policy = ['expiration' => gmdate('Y-m-d\\TH:i:s\\Z', $ttd), 'conditions' => [['bucket' => $this->bucket]]]; // Setup basic form $this->formAttributes = ['action' => $this->generateUrl($options), 'method' => 'POST', 'enctype' => 'multipart/form-data']; $this->formInputs = ['AWSAccessKeyId' => $this->client->getCredentials()->getAccessKeyId()]; // Add success action status $status = (int) $options->get('success_action_status'); if ($status && in_array($status, [200, 201, 204])) { $this->formInputs['success_action_status'] = (string) $status; $policy['conditions'][] = ['success_action_status' => (string) $status]; unset($options['success_action_status']); } // Add other options foreach ($options as $key => $value) { $value = (string) $value; if ($value[0] === '^') { $value = substr($value, 1); $this->formInputs[$key] = $value; $value = preg_replace('/\\$\\{(\\w*)\\}/', '', $value); $policy['conditions'][] = ['starts-with', '$' . $key, $value]; } else { $this->formInputs[$key] = $value; $policy['conditions'][] = [$key => $value]; } } // Handle the policy $policy = is_callable($policyCallback) ? $policyCallback($policy, $this) : $policy; $this->jsonPolicy = $rawJsonPolicy ?: json_encode($policy); $this->applyPolicy(); return $this; }
public static function factory($config = []) { $default = []; $required = ['apikey']; foreach ($required as $value) { if (empty($config[$value])) { throw new InvalidArgumentException("Argument '{$value}' must not be blank."); } } $config = Collection::fromConfig($config, $default, $required); $baseClient = new Client($config->toArray()); $baseClient->setDefaultOption('query', ['apikey' => urldecode($config['apikey'])]); $description = new Description(static::getServiceDescription()); $serializer = new Serializer($description, ['put' => new PutLocation('put')]); $client = new static($baseClient, $description, ['serializer' => $serializer]); $client->getEmitter()->on('prepared', function (PreparedEvent $event) { $request = $event->getTransaction()->request; if (!$request->hasHeader('Content-Type')) { $request->setHeader('Content-Type', 'application/json'); } }); return $client; }
/** * @param array $config * @param ClientInterface|null $client * @param DescriptionInterface|null $description */ public function __construct(array $config = [], ClientInterface $client = null, DescriptionInterface $description = null) { $mandatoryAttributes = ['api_token']; // unless a definition is explicitly provided, the base url is mandatory. if (!$description) { $mandatory[] = 'base_url'; } // Create a collection object with defaults and required params set $config = Collection::fromConfig($config, ['max_retries' => 3], $mandatoryAttributes); if (!$client) { $client = $this->loadHttpClient($config); } if (!$description) { $description = $this->loadDescription($config); } // KLUDGE // hold on to the authentication subscriber // so we can update the JWT on it later in case // refreshApiToken() gets run. // TODO: look for a more elegant solution to this problem. // [ST 2015/07/24] $this->auth = $this->attachAuthenticationSubscriber($client, $config->get('api_token')); parent::__construct($client, $description, $config->toArray()); }
/** * Constructor * * @param array $config */ public function __construct(array $config = []) { $defaults = ['write_key' => null, 'version' => 'v1', 'batching' => 'request', 'log_file' => null, 'max_queue_size' => 10000, 'batch_size' => 100]; // Create Configuration $config = Collection::fromConfig($config, $defaults, ['write_key', 'version', 'batching']); // Load versioned Service Description $description = $this->loadServiceDescription(__DIR__ . '/Description/segment.io.%s.php', $config->get('version')); // Allow the Adapter to be set $httpConfig = $config->hasKey('adapter') ? ['adapter' => $config->get('adapter')] : []; // Create the Client parent::__construct(new HttpClient($httpConfig), $description, $config->toArray()); // Set Basic Auth $this->getHttpClient()->setDefaultOption('auth', [$config->get('write_key'), null]); // Set the content type header to use "application/json" for all requests $this->getHttpClient()->setDefaultOption('headers', array('Content-Type' => 'application/json')); // Default the Version $this->setConfig('defaults/version', $this->getDescription()->getApiVersion()); if ($config->get('batching') == 'request') { $this->getEmitter()->attach(new BatchRequestSubscriber($this->getDescription(), ['max_queue_size' => $config->get('max_queue_size'), 'batch_size' => $config->get('batch_size')])); } if ($config->get('batching') == 'file') { $this->getEmitter()->attach(new BatchFileSubscriber($this->getDescription(), ['filename' => $config->get('log_file')])); } }
public function testPreparesFromConfig() { $c = Collection::fromConfig(array('a' => '123', 'base_url' => 'http://www.test.com/'), array('a' => 'xyz', 'b' => 'lol'), array('a')); $this->assertInstanceOf('GuzzleHttp\\Collection', $c); $this->assertEquals(array('a' => '123', 'b' => 'lol', 'base_url' => 'http://www.test.com/'), $c->toArray()); try { $c = Collection::fromConfig(array(), array(), array('a')); $this->fail('Exception not throw when missing config'); } catch (\InvalidArgumentException $e) { } }
/** * Create a new Simple plugin. * * The configuration array expects one option * - key: required, otherwise InvalidArgumentException is thrown * * @param array $config Configuration array */ public function __construct(array $config) { $this->config = Collection::fromConfig($config, [], ['key']); }
/** * Create a signed Amazon CloudFront URL. * * This method accepts an array of configuration options: * * - url: (string) URL of the resource being signed (can include query * string and wildcards). For example: rtmp://s5c39gqb8ow64r.cloudfront.net/videos/mp3_name.mp3 * http://d111111abcdef8.cloudfront.net/images/horizon.jpg?size=large&license=yes * - policy: (string) JSON policy. Use this option when creating a signed * URL for a custom policy. * - expires: (int) UTC Unix timestamp used when signing with a canned * policy. Not required when passing a custom 'policy' option. * - key_pair_id: (string) The ID of the key pair used to sign CloudFront * URLs for private distributions. * - private_key: (string) The filepath ot the private key used to sign * CloudFront URLs for private distributions. * * @param array $options Array of configuration options used when signing * * @return string Signed URL with authentication parameters * @throws \InvalidArgumentException if url, key_pair_id, or private_key * were not specified. * @link http://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/WorkingWithStreamingDistributions.html */ public function getSignedUrl(array $options) { $options = Collection::fromConfig($options, [], ['url', 'key_pair_id', 'private_key']); $UrlSigner = new UrlSigner($options['key_pair_id'], $options['private_key']); return $UrlSigner->getUrlSigner($options['url'], $options['expires'], $options['policy']); }
/** * Builds the authorization Uri that the user should be redirected to. * * @param $config configuration options that customize the return url * @return GuzzleHttp::Url the authorization Url. */ public function buildFullAuthorizationUri(array $config = null) { if (is_null($this->getAuthorizationUri())) { throw new \InvalidArgumentException('requires an authorizationUri to have been set'); } $defaults = ['response_type' => 'code', 'access_type' => 'offline', 'client_id' => $this->clientId, 'redirect_uri' => $this->redirectUri, 'state' => $this->state, 'scope' => $this->getScope()]; $params = new Collection($defaults); if (!is_null($config)) { $params = Collection::fromConfig($config, $defaults, []); } // Validate the auth_params if (is_null($params->get('client_id'))) { throw new \InvalidArgumentException('missing the required client identifier'); } if (is_null($params->get('redirect_uri'))) { throw new \InvalidArgumentException('missing the required redirect URI'); } if ($params->hasKey('prompt') && $params->hasKey('approval_prompt')) { throw new \InvalidArgumentException('prompt and approval_prompt are mutually exclusive'); } // Construct the uri object; return it if it is valid. $result = clone $this->authorizationUri; if (is_string($result)) { $result = Url::fromString($this->getAuthorizationUri()); } $result->getQuery()->merge($params); if ($result->getScheme() != 'https') { throw new \InvalidArgumentException('Authorization endpoint must be protected by TLS'); } return $result; }
/** * Instantiates a new SyneriseCoupon instance. * @param array $config */ public function __construct($config = array()) { parent::__construct($config); $config = Collection::fromConfig($config, static::getDefaultConfig(), static::$required); $this->configure($config); }
/** * Construct the Google Client. * * @param $config Google_Config or string for the ini file to load */ public function __construct($config = array()) { $this->config = Collection::fromConfig($config, ['application_name' => '', 'base_path' => self::API_BASE_PATH, 'client_id' => '', 'client_secret' => '', 'redirect_uri' => null, 'state' => null, 'developer_key' => '', 'use_application_default_credentials' => false, 'hd' => '', 'prompt' => '', 'openid.realm' => '', 'include_granted_scopes' => null, 'login_hint' => '', 'request_visible_actions' => '', 'access_type' => 'online', 'approval_prompt' => 'auto', 'retry' => array()]); }
/** * @param ClientInterface $client * @param array $config */ public function __construct(ClientInterface $client, array $config = []) { $this->client = $client; $this->config = Collection::fromConfig($config, $this->getDefaults(), $this->getRequired()); }
/** * @param array $config */ public function __construct(array $config) { $this->config = Collection::fromConfig($config, ['client_secret' => null, 'redirect_uri' => null, 'oauth_token' => null], ['client_id']); }
/** * Create a new OAuth 1.0 plugin. * * The configuration array accepts the following options: * * - request_method: Consumer request method. One of 'header' or 'query'. * Defaults to 'header'. * - callback: OAuth callback * - consumer_key: Consumer key string. Defaults to "anonymous". * - consumer_secret: Consumer secret. Defaults to "anonymous". * - token: Client token * - token_secret: Client secret token * - verifier: OAuth verifier. * - version: OAuth version. Defaults to '1.0'. * - realm: OAuth realm. * - signature_method: Signature method. One of 'HMAC-SHA1', 'RSA-SHA1', or * 'PLAINTEXT'. Defaults to 'HMAC-SHA1'. * * @param array $config Configuration array. */ public function __construct($config) { $this->config = Collection::fromConfig($config, ['version' => '1.0', 'request_method' => self::REQUEST_METHOD_HEADER, 'consumer_key' => 'anonymous', 'consumer_secret' => 'anonymous', 'signature_method' => self::SIGNATURE_METHOD_HMAC], ['signature_method', 'version', 'consumer_key', 'consumer_secret']); }
/** * Create a new KNVB Dataservice Authentication Subscriber * * The configuration array must contain the following items: * * - pathname: Unique pathname for the club * - key: The secret API key * - session_id: Session ID from the initialisation * * @param array $config Configuration array. */ public function __construct($config) { $this->config = Collection::fromConfig($config, [], ['key', 'session_id']); }