/** * @param string $name * @param array $args * * @return FutureInterface|mixed|null */ public function request($name, array $args = []) { $args = array_merge($this->getDefaultArgs(), $args); $command = $this->guzzleClient->getCommand($name, $args); $response = $this->guzzleClient->execute($command); return $response; }
/** * @expectedException \GuzzleHttp\Command\Exception\CommandException * @expectedExceptionMessage 404 */ public function testDoesNotAddResultWhenExceptionIsPresent() { $description = new Description(['operations' => ['foo' => ['uri' => 'http://httpbin.org/{foo}', 'httpMethod' => 'GET', 'responseModel' => 'j', 'parameters' => ['bar' => ['type' => 'string', 'required' => true, 'location' => 'uri']]]]]); $client = new GuzzleClient(new Client(), $description); $client->getHttpClient()->getEmitter()->attach(new Mock([new Response(404)])); $client->foo(['bar' => 'baz']); }
/** * @expectedException \GuzzleHttp\Command\Exception\CommandException * @expectedExceptionMessage Validation errors: [bar] must be of type string */ public function testValidatesAdditionalParameters() { $description = new Description(['operations' => ['foo' => ['uri' => 'http://httpbin.org', 'httpMethod' => 'GET', 'responseModel' => 'j', 'additionalParameters' => ['type' => 'string']]]]); $client = new GuzzleClient(new Client(), $description); $val = new ValidateInput($description); $event = new InitEvent(new CommandTransaction($client, $client->getCommand('foo', ['bar' => new \stdClass()]))); $val->onInit($event); }
/** * @return string $sessionToken * @throws \Betfair\Exception\BetfairLoginException */ private function login() { /** @var Response $result */ $result = $this->betfairGuzzleClient->betfairLogin($this->builtLoginArrayParameters()); if ($result && $result->getStatusCode() == 200) { return $this->extractSessionTokenFromResponseBody($result->getBody()); } throw new BetfairLoginException(sprintf("Error during credentials verification.")); }
public function createGuzzleClient(array $config) { $config = new Collection($config); $httpClient = new \GuzzleHttp\Client(); $description = new Description($this->getDescription()); $serializer = new Serializer($description, ['json_body' => new JsonBodyLocation('body')]); $client = new GuzzleClient($httpClient, $description, ['serializer' => $serializer]); $client->getEmitter()->attach(new Authorization($config->get('token'), $config->get('secret'))); return $client; }
function it_should_return_recommendations(GuzzleClient $client, ResponseParser $parser, RecommendationFactory $factory, Command $command) { $parameters = ['id' => '1', 'limit' => 30]; $client->getCommand('recommendations', $parameters)->willReturn($command); $results = [['id' => '1', 'uuid' => 'abc', ['score' => ['totalScore' => 0, 'scoreParts' => []]]]]; $client->execute($command)->willReturn($results); $parser->parse($results)->willReturn($results); $factory->getRecommendation(['id' => '1', 'uuid' => 'abc', ['score' => ['totalScore' => 0, 'scoreParts' => []]]])->willReturn(new Recommendation('1', 'abc', new Score())); $recommendationResult = $this->getRecommendations($parameters); $recommendationResult->shouldBeArray(); }
/** * @param HttpClientInterface $client * @param ServiceDescriptionInterface $description */ public function __construct(HttpClientInterface $client, ServiceDescriptionInterface $description) { $config = array('process' => false); parent::__construct($client, $description, $config); $emitter = $this->getEmitter(); $emitter->attach(new Subscriber\ProcessResponse($description)); }
/** * @param string $commandName * @param array $params * * @return array */ public function executeCommand($commandName, array $params = array()) { try { $command = empty($params) ? $this->client->getCommand($commandName) : $this->client->getCommand($commandName, $params); $command->getEmitter()->on('process', function (ProcessEvent $event) { $event->setResult($event->getResponse()); }); $result = $this->client->execute($command); if ($result->getStatusCode() != 200) { throw new \Exception($result->getReasonPhrase()); } } catch (\Exception $e) { return array("status" => "error", "message" => $e->getMessage()); } return $result ? array("status" => "success", "message" => $result) : array("status" => "error", "message" => "Empty response after API call."); }
/** * @param array $config * @throws \Exception */ public function __construct(array $config = []) { // Apply some defaults. $config = array_merge($config, ['max_retries' => 3]); // Create the client. parent::__construct($this->getHttpClientFromConfig($config), $this->getDescriptionFromConfig($config), $config); }
public function getMessage($id, $inboxId = null) { if ($inboxId === null) { $inboxId = $this->getDefaultInboxID(); } return parent::getMessage(['id' => $id, 'inbox_id' => $inboxId]); }
/** * @param array $config * @param string $env * @throws \Exception */ public function __construct(array $config = [], $env = self::ENV_PROD) { /* * Make sure ENV is valid */ if (!in_array($env, [self::ENV_PROD, self::ENV_STAGE, self::ENV_MOCK])) { throw new \Exception('Invalid environment', 1462566788); } /* * Check that consumerId and privateKey are set */ if (!isset($config['consumerId']) || !isset($config['privateKey'])) { throw new \Exception('Configuration missing consumerId or privateKey', 1466965269); } // Set ENV $this->env = $env; // Apply some defaults. $config = array_merge_recursive($config, ['max_retries' => 3, 'http_client_options' => ['defaults' => ['auth' => [$config['consumerId'], $config['privateKey']]]]]); // If an override base url is not provided, determine proper baseurl from env if (!isset($config['description_override']['baseUrl'])) { $config = array_merge_recursive($config, ['description_override' => ['baseUrl' => $this->getEnvBaseUrl($env)]]); } // Create the client. parent::__construct($this->getHttpClientFromConfig($config), $this->getDescriptionFromConfig($config), $config); // Ensure that ApiVersion is set. $this->setConfig('defaults/ApiVersion', $this->getDescription()->getApiVersion()); }
/** * @param ClientInterface $client * @param DescriptionInterface $description * @param array $responseClasses * @param Serializer $serializer * @param array $config */ public function __construct(ClientInterface $client, DescriptionInterface $description, array $responseClasses, Serializer $serializer, array $config = []) { $this->client = $client; $this->responseClasses = $responseClasses; $this->serializer = $serializer; parent::__construct($client, $description, $config); }
/** * @param array $config */ public function __construct(array $config = []) { // Apply some defaults. $config += ['max_retries' => 3]; // Create the Smartsheet client. parent::__construct($this->getHttpClientFromConfig($config), $this->getDescriptionFromConfig($config), $config); // Ensure that the credentials are set. $this->applyCredentials($config); }
/** * Set custom guzzle subscriber (ie. History, mock, etc) * * @param SubscriberInterface $subscriber * @return static */ public function setClientSubscriber(\GuzzleHttp\Event\SubscriberInterface $subscriber) { if (!$this->serviceClient) { $this->getBaseClient()->getEmitter()->attach($subscriber); } else { $this->serviceClient->getEmitter()->attach($subscriber); } return $this; }
public static function factory($apiKey, array $config = []) { $defaultConfig = ['defaults' => ['headers' => ['User-Agent' => 'php-kissmetrics-api/1.0.0 +https://github.com/ricbra/php-kissmetrics-api']]]; $client = new Client(self::mergeRecursive($defaultConfig, $config)); $service = (include __DIR__ . '/../../resources/service.php'); $description = new Description($service); $client = new GuzzleClient($client, $description); // Inject key & convert bools to int so false doesnt get lost $client->getEmitter()->on('init', function (InitEvent $event) use($apiKey) { $command = $event->getCommand(); $command['_k'] = $apiKey; foreach ($command->toArray() as $key => $value) { if (is_bool($value)) { $command[$key] = (int) $value; } } }, 'first'); return $client; }
/** * Class constructor. * * @param string|null $apiKey API key (optional). * @param \GuzzleHttp\ClientInterface|null $httpClient Alternative Guzzle HTTP client (optional). */ public function __construct($apiKey = null, GuzzleHttp_ClientInterface $httpClient = null) { // Embed.ly API description $description = json_decode(file_get_contents(__DIR__ . '/description.json'), true); parent::__construct($httpClient ?: new GuzzleHttp_Client(), new Description($description)); $this->setApiKey($apiKey); $this->getHttpClient()->getEmitter()->once('before', function (BeforeEvent $event) { $this->getBeforeEvent($event); }); }
/** * @param array $config */ public function __construct(array $config = []) { // Apply some defaults. $config += ['max_retries' => 3, 'description_path' => __DIR__ . '/jira-api.php']; // Create the Jira client. parent::__construct($this->getHttpClientFromConfig($config), $this->getDescriptionFromConfig($config), $config); // Ensure that the credentials are set. $this->applyCredentials($config); // Ensure that ApiVersion is set. $this->setConfig('defaults/ApiVersion', $this->getDescription()->getApiVersion()); }
public function __construct(array $config = []) { $resolver = new OptionsResolver(); $this->configureOptionResolver($resolver); // Params validation $options = $resolver->resolve($config); // initialisation du client standard Guzzle $client = new Client(["defaults" => ["auth" => [$options["username"], $options["password"]]], "base_url" => $options["base_url"], "debug" => $options["debug"]]); // $client->getEmitter()->attach(new LogSubscriber()); $description = new Description(json_decode(file_get_contents(__DIR__ . '/../Resources/config/client.json'), true)); parent::__construct($client, $description); }
/** * @param array $parameters * @return \GraphAwareReco\Domain\Model\Recommendation[] * @throws ServerErrorException * @throws UnFoundItemException */ public function getRecommendations(array $parameters) { $command = $this->client->getCommand('recommendations', $parameters); try { $result = $this->client->execute($command); } catch (CommandClientException $ex) { if ($ex->getResponse()->getStatusCode() == 404) { throw new UnFoundItemException($parameters, $ex->getResponse()->getBody()); } elseif ($ex->getResponse()->getStatusCode() == 500) { throw new ServerErrorException($parameters, $ex->getResponse()->getBody()); } else { throw new ServerErrorException($parameters, $ex->getResponse()->getBody()); } } $recommendationResults = $this->parser->parse($result); $recommendations = []; foreach ($recommendationResults as $recommendation) { $recommendations[] = $this->factory->getRecommendation($recommendation); } return $recommendations; }
/** * @param CommandInterface $command * * @return \GuzzleHttp\Ring\Future\FutureInterface|mixed|null * @throws \Exception */ public function execute(CommandInterface $command) { try { $result = parent::execute($command); return $result['result']; } catch (RequestException $e) { if ($e->hasResponse() !== null) { throw new \Exception($e->getResponse()->getBody()->__toString()); } throw $e; } }
/** * @param array $config */ public function __construct(array $config = []) { // Apply some defaults. $config += ['max_retries' => 3]; // Create the client. parent::__construct($this->getHttpClientFromConfig($config), $this->getDescriptionFromConfig($config), $config); // Ensure that the credentials are set. $this->applyCredentials($config); // Apply the data type (if provided). $this->applyDataType($config); // Ensure that ApiVersion is set. $this->setConfig('defaults/ApiVersion', $this->getDescription()->getApiVersion()); }
/** * @param string $pApiKey * @param \GuzzleHttp\Command\Guzzle\Description|string $pSubscription * * @throws InvalidArgumentException */ public function __construct($pApiKey, $pSubscription = Enum\Subscription::KEY_DEVELOPER) { if (empty($pApiKey)) { throw new InvalidArgumentException("API key must not be empty."); } if (false === Enum\Subscription::IsValid($pSubscription)) { throw new InvalidArgumentException("Subscription provided '{$pSubscription}' is invalid."); } $service_config = (require 'Resources/fantasy_data_api.php'); $description = new Description($service_config); $client = $this->CreateHttpClient(); parent::__construct($client, $description); $this->setConfig('defaults/Subscription', $pSubscription); $this->setConfig('defaults/key', $pApiKey); }
/** * @param string $baseUri TelecomsCloud API base URI, usually https://api.telecomscloud.com * @param bool $proxy optional http proxy address for development & testing */ public function __construct($baseUri, $proxy = false) { $config = []; if ($proxy) { $config['default']['proxy'] = $proxy; $config['default']['debug'] = true; } $serviceDescription = json_decode(file_get_contents(__DIR__ . '/tc-service.json'), true); $description = new Description($serviceDescription); $client = new GuzClient(['base_url' => $baseUri]); $client->setDefaultOption('allow_redirects', false); if ($proxy) { $client->setDefaultOption('proxy', $proxy); } $this->guzzleClient = $client; parent::__construct($client, $description, $config); }
/** * {@inheritDoc} * * The additional array keys and values are available config options: * - base_url: Base URL of web service * - customer_id: a default customerID to use */ public function __construct(Client $client, $config = array()) { $descriptionJson = json_decode(file_get_contents(__DIR__ . '/service.json'), true); if (empty($config['base_url'])) { $config['base_url'] = 'https://www.eway.com.au/gateway_cvn/xmlpayment.asp'; } $descriptionJson['baseUrl'] = $config['base_url']; $description = new Description($descriptionJson); parent::__construct($client, $description, $config); if (!empty($config['customer_id'])) { $this->getEmitter()->on('prepare', function (PrepareEvent $event) use($config) { $command = $event->getCommand(); if (empty($command['customerID'])) { $command['customerID'] = $config['customer_id']; } }, 'first'); } }
/** * @param array $config * @param string $env * @throws \Exception */ public function __construct(array $config = [], $env = self::ENV_PROD) { if (!in_array($env, [self::ENV_PROD, self::ENV_MOCK])) { throw new \Exception('Invalid environment', 1462566788); } $this->env = $env; // Apply some defaults. $config = array_merge_recursive($config, ['max_retries' => 3]); // If an override base url is not provided, determine proper baseurl from env if (!isset($config['description_override']['baseUrl'])) { $config = array_merge_recursive($config, ['description_override' => ['baseUrl' => $this->getEnvBaseUrl($env)]]); } // Create the client. parent::__construct($this->getHttpClientFromConfig($config), $this->getDescriptionFromConfig($config), $config); // Add auth header $this->applyCredentials($config); // Ensure that ApiVersion is set. $this->setConfig('defaults/ApiVersion', $this->getDescription()->getApiVersion()); }
/** * @dataProvider xmlProvider */ public function testSerializesXml(array $operation, array $input, $xml) { $operation['uri'] = 'http://httpbin.org'; $client = new GuzzleClient(new Client(), new Description(['operations' => ['foo' => $operation]])); $request = null; $command = $client->getCommand('foo', $input); $command->getEmitter()->on('prepare', function (PrepareEvent $event) use(&$request) { $request = $event->getRequest(); $event->getRequest()->getEmitter()->on('before', function (BeforeEvent $e) { $e->intercept(new Response(200)); }); }); $client->execute($command); if (!empty($input)) { $this->assertEquals('application/xml', $request->getHeader('Content-Type')); } else { $this->assertEquals('', (string) $request->getHeader('Content-Type')); } $body = str_replace(array("\n", "<?xml version=\"1.0\"?>"), '', (string) $request->getBody()); $this->assertEquals($xml, $body); }
/** * @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 testVisitsNestedProperties() { $hclient = new Client(); $hclient->getEmitter()->on('before', function (BeforeEvent $event) { $json = ['nested' => ['foo' => 'abc', 'bar' => 123, 'bam' => ['abc' => 456]], 'baz' => 'boo']; $response = new Response(200, ['Content-Type' => 'application/json'], Stream::factory(json_encode($json))); $event->intercept($response); }); $description = new Description(['operations' => ['foo' => ['uri' => 'http://httpbin.org', 'httpMethod' => 'GET', 'responseModel' => 'j']], 'models' => ['j' => ['type' => 'object', 'properties' => ['nested' => ['location' => 'json', 'type' => 'object', 'properties' => ['foo' => ['type' => 'string'], 'bar' => ['type' => 'number'], 'bam' => ['type' => 'object', 'properties' => ['abc' => ['type' => 'number']]]]]], 'additionalProperties' => ['location' => 'json', 'type' => 'string', 'filters' => ['strtoupper']]]]]); $client = new GuzzleClient($hclient, $description); $result = $client->foo(); $expected = ['nested' => ['foo' => 'abc', 'bar' => 123, 'bam' => ['abc' => 456]], 'baz' => 'BOO']; $this->assertEquals($expected, $result->toArray()); }
public function __call($name, array $arguments) { if (in_array($name, $this->executeWithBody)) { return $this->executeRequestWithBody($name, $arguments[0]); } return parent::__call($name, $arguments); }