public function testDownloaderDownloadsData() { $handler = HandlerStack::create(new MockHandler([new Response(200, [], file_get_contents(__DIR__ . '/data/example-response.json'))])); $downloader = new Downloader('validToken', new Client(['handler' => $handler])); $transactionList = $downloader->downloadSince(new \DateTime('-1 week')); $this->assertInstanceOf('\\FioApi\\TransactionList', $transactionList); }
public function testSend() { $self = $this; $mockRequestData = ['foo' => 'bar', 'token' => self::TOKEN]; $mockResponseData = ['ok' => true, 'foo' => 'bar']; $handler = HandlerStack::create(new MockHandler([new Response(200, [], json_encode($mockResponseData))])); $historyContainer = []; $history = Middleware::history($historyContainer); $handler->push($history); $apiClient = new ApiClient(self::TOKEN, new Client(['handler' => $handler])); $apiClient->addRequestListener(function (RequestEvent $event) use(&$eventsDispatched, $mockRequestData, $self) { $eventsDispatched[ApiClient::EVENT_REQUEST] = true; $self->assertEquals($mockRequestData, $event->getRawPayload()); }); $apiClient->addResponseListener(function (ResponseEvent $event) use(&$eventsDispatched, $mockResponseData, $self) { $eventsDispatched[ApiClient::EVENT_RESPONSE] = true; $self->assertEquals($mockResponseData, $event->getRawPayloadResponse()); }); $mockPayload = new MockPayload(); $mockPayload->setFoo('bar'); $apiClient->send($mockPayload); $transaction = $historyContainer[0]; $requestUrl = (string) $transaction['request']->getUri(); $requestContentType = $transaction['request']->getHeader('content-type')[0]; parse_str($transaction['request']->getBody(), $requestBody); $responseBody = json_decode($transaction['response']->getBody(), true); $this->assertEquals(ApiClient::API_BASE_URL . 'mock', $requestUrl); $this->assertEquals('application/x-www-form-urlencoded', $requestContentType); $this->assertEquals($mockRequestData, $requestBody); $this->assertEquals($mockResponseData, $responseBody); $this->assertArrayHasKey(ApiClient::EVENT_REQUEST, $eventsDispatched); $this->assertArrayHasKey(ApiClient::EVENT_RESPONSE, $eventsDispatched); }
/** * * @return Client */ protected function getClient(array $responseQueue = []) { $mock = new MockHandler($responseQueue); $handler = HandlerStack::create($mock); $client = new Client(['handler' => $handler]); return $client; }
/** * TestClient constructor. * * @param MockHandler $mock * @param IdGeneratorInterface $idGenerator */ public function __construct(MockHandler $mock, IdGeneratorInterface $idGenerator) { $handler = HandlerStack::create($mock); $this->idGenerator = $idGenerator; $guzzle = new Client(['handler' => $handler]); $this->client = new JsonRpcClient($guzzle, new Uri('http://localhost/'), $this->idGenerator); }
private function getMockClient(array $response) { $mock = new MockHandler($response); $handler = HandlerStack::create($mock); $client = new Client(['handler' => $handler]); return $client; }
public static function setUpBeforeClass() { $mock = new MockHandler([new Response(200, [], file_get_contents(__DIR__ . '/SomeApiResponse.json')), new Response(200, [], file_get_contents(__DIR__ . '/SomeEmptyApiResponse.json')), new Response(200, [], file_get_contents(__DIR__ . '/SomeEmptyApiResponseWithUnsupportedEvents.json'))]); $handler = HandlerStack::create($mock); $client = new Client(['handler' => $handler]); self::$apiEventStore = new GuzzleApiEventStore($client, new SomeSerializer()); }
/** * Constructs a Solr client from input params. * * @return Client */ protected function getClient(InputInterface $input, OutputInterface $output) { if (isset($this->client)) { return $this->client; } $baseURL = $input->getOption('url'); $username = $input->getOption('username'); $password = $input->getOption('password'); // Add trailing slash if one doesn't exist if ($baseURL[strlen($baseURL) - 1] !== '/') { $baseURL .= '/'; } $output->writeln("Solr URL: <info>{$baseURL}</info>"); if (!empty($username)) { $output->writeln("Basic auth: <info>{$username}</info>"); } // Middleware which logs requests $before = function (Request $request, $options) use($output) { $url = $request->getUri(); $method = $request->getMethod(); $output->writeln(sprintf("<info>%s</info> %s ", $method, $url)); }; // Setup the default handler stack and add the logging middleware $stack = HandlerStack::create(); $stack->push(Middleware::tap($before)); // Guzzle options $options = ['base_uri' => $baseURL, 'handler' => $stack]; if (isset($username)) { $options['auth'] = [$username, $password]; } $guzzle = new GuzzleClient($options); return new Client($guzzle); }
private function initClient() { $handlerStack = HandlerStack::create(); $handlerStack->push(MiddlewareBuilder::factoryForPing($this->logger, self::MAX_RETRIES)); $handlerStack->push(Middleware::log($this->logger, new MessageFormatter('{hostname} {req_header_User-Agent} - [{ts}] \\"{method} {resource} {protocol}/{version}\\" {code} {res_header_Content-Length}'))); $this->client = new \GuzzleHttp\Client(['base_uri' => $this->storageApi->getApiUrl(), 'handler' => $handlerStack]); }
public function register(Application $app) { $app['guzzle.base_url'] = '/'; $app['guzzle.api_version'] = $app->share(function () use($app) { return version_compare(Client::VERSION, '6.0.0', '>=') ? 6 : 5; }); if (!isset($app['guzzle.handler_stack'])) { $app['guzzle.handler_stack'] = $app->share(function () { return HandlerStack::create(); }); } /** @deprecated Remove when Guzzle 5 support is dropped */ if (!isset($app['guzzle.plugins'])) { $app['guzzle.plugins'] = []; } // Register a simple Guzzle Client object (requires absolute URLs when guzzle.base_url is unset) $app['guzzle.client'] = $app->share(function () use($app) { if ($app['guzzle.api_version'] === 5) { $options = ['base_url' => $app['guzzle.base_url']]; $client = new Client($options); foreach ($app['guzzle.plugins'] as $plugin) { $client->addSubscriber($plugin); } } else { $options = ['base_uri' => $app['guzzle.base_url'], 'handler' => $app['guzzle.handler_stack']]; $client = new Client($options); } return $client; }); }
protected function initClient() { $handlerStack = HandlerStack::create(); /** @noinspection PhpUnusedParameterInspection */ $handlerStack->push(Middleware::retry(function ($retries, RequestInterface $request, ResponseInterface $response = null, $error = null) { return $response && $response->getStatusCode() == 503; }, function ($retries) { return rand(60, 600) * 1000; })); /** @noinspection PhpUnusedParameterInspection */ $handlerStack->push(Middleware::retry(function ($retries, RequestInterface $request, ResponseInterface $response = null, $error = null) { if ($retries >= self::RETRIES_COUNT) { return false; } elseif ($response && $response->getStatusCode() > 499) { return true; } elseif ($error) { return true; } else { return false; } }, function ($retries) { return (int) pow(2, $retries - 1) * 1000; })); $handlerStack->push(Middleware::cookies()); if ($this->logger) { $handlerStack->push(Middleware::log($this->logger, $this->loggerFormatter)); } $this->guzzle = new \GuzzleHttp\Client(array_merge(['handler' => $handlerStack, 'cookies' => true], $this->guzzleOptions)); }
public function testSend() { $container = []; $history = Middleware::history($container); $mockResponseData = json_encode(['ok' => true, 'foo' => 'bar']); $mock = new MockHandler([new Response(200, [], $mockResponseData)]); $stack = HandlerStack::create($mock); $stack->push($history); $client = new Client(['handler' => $stack]); $mockPayload = new MockPayload(); $foo = 'who:(search+query+OR+other+search+query)'; $mockPayload->setFoo($foo); $apiClient = new ApiClient(self::API_KEY, $client); $payloadResponse = $apiClient->send($mockPayload); $transaction = array_pop($container); // Assert response is of type MockPayloadResponse $this->assertInstanceOf('Colada\\Europeana\\Tests\\Test\\Payload\\MockPayloadResponse', $payloadResponse); // Assert if the responses match up. $transaction['response']->getBody(); $this->assertEquals($mockResponseData, $transaction['response']->getBody()); // Assert if the URL is unfuddled. $expectedRequestUri = sprintf('http://europeana.eu/api/v2/mock.json?foo=%s&wskey=%s', $foo, self::API_KEY); $requestUri = $transaction['request']->getUri(); $this->assertEquals($expectedRequestUri, $requestUri); }
public function testBasicClient() { $mock = new MockHandler([new Response(200, ['X-Foo' => 'Bar'], "{\"foo\":\"bar\"}")]); $container = []; $history = Middleware::history($container); $stack = HandlerStack::create($mock); $stack->push($history); $http_client = new Client(['handler' => $stack]); $client = new BuuyersClient('u', 'p'); $client->setClient($http_client); $client->companies->getCompany(1); foreach ($container as $transaction) { $basic = $transaction['request']->getHeaders()['Authorization'][0]; $this->assertTrue($basic == "Basic dTpw"); $method = $transaction['request']->getMethod(); $this->assertEquals($method, 'GET'); //> GET if ($transaction['response']) { $statusCode = $transaction['response']->getStatusCode(); $this->assertEquals(200, $statusCode); //> 200, 200 } elseif ($transaction['error']) { echo $transaction['error']; //> exception } } }
public static function get(array $options, Oauth1 $oauth1) { $stack = HandlerStack::create(); $stack->unshift($oauth1); $options['handler'] = $stack; return new Client($options); }
/** * @return \GuzzleHttp\HandlerStack */ public function getHandlerStack() { $stack = HandlerStack::create(); $stack->setHandler(new CurlHandler()); $stack->push(signature_middleware_factory($this->ctx)); return $stack; }
public function setUp() { // Create default HandlerStack $stack = HandlerStack::create(function (RequestInterface $request, array $options) { switch ($request->getUri()->getPath()) { case '/etag': if ($request->getHeaderLine("If-None-Match") == 'MyBeautifulHash') { return new FulfilledPromise(new Response(304)); } return new FulfilledPromise((new Response())->withHeader("Etag", 'MyBeautifulHash')); case '/etag-changed': if ($request->getHeaderLine("If-None-Match") == 'MyBeautifulHash') { return new FulfilledPromise((new Response())->withHeader("Etag", 'MyBeautifulHash2')); } return new FulfilledPromise((new Response())->withHeader("Etag", 'MyBeautifulHash')); case '/stale-while-revalidate': if ($request->getHeaderLine("If-None-Match") == 'MyBeautifulHash') { return new FulfilledPromise((new Response(304))->withHeader("Cache-Control", 'max-age=10')); } return new FulfilledPromise((new Response())->withHeader("Etag", 'MyBeautifulHash')->withHeader("Cache-Control", 'max-age=1')->withAddedHeader("Cache-Control", 'stale-while-revalidate=60')); } throw new \InvalidArgumentException(); }); // Add this middleware to the top with `push` $stack->push(CacheMiddleware::getMiddleware(), 'cache'); // Initialize the client with the handler option $this->client = new Client(['handler' => $stack]); CacheMiddleware::setClient($this->client); }
public function __construct() { $handler = new CurlHandler(); $this->stack = HandlerStack::create($handler); // Wrap w/ middleware $this->guzzle = new Guzzle(['base_uri' => self::MAILCHIMP_BASE_URL]); }
protected function getHttpSettings() { $handlers = HandlerStack::create(); $handlers->push(new Oauth1($this->credentials)); $settings = ['defaults' => ['auth' => $this->accessToken ? 'oauth2' : 'oauth', 'handler' => $handlers]]; return array_merge(parent::getHttpSettings(), $settings); }
protected function setUp() { $this->mock = new \GuzzleHttp\Handler\MockHandler(); $handler = \GuzzleHttp\HandlerStack::create($this->mock); $client = new \GuzzleHttp\Client(['handler' => $handler]); $this->geo = new \Fgms\Distributor\GoogleMapsGeocoder($this->api_key, new \Fgms\Distributor\GoogleMapsGeocoderExceptionAmbiguityResolutionStrategy(), $client); }
/** * Register method. */ public function register() { // Configuring all guzzle clients. $this->app->bind(ClientInterface::class, function () { // Guzzle client return new Client(['handler' => $this->app->make(HandlerStack::class)]); }); $this->app->alias(ClientInterface::class, Client::class); // Bind if needed. $this->app->bindIf(HandlerStack::class, function () { return HandlerStack::create(); }); // If resolved, by this SP or another, add some layers. $this->app->resolving(HandlerStack::class, function (HandlerStack $stack) { /** @var \DebugBar\DebugBar $debugBar */ $debugBar = $this->app->make('debugbar'); $stack->push(new Middleware(new Profiler($timeline = $debugBar->getCollector('time')))); $stack->unshift(new ExceptionMiddleware($debugBar->getCollector('exceptions'))); /** @var \GuzzleHttp\MessageFormatter $formatter */ $formatter = $this->app->make(MessageFormatter::class); $stack->unshift(GuzzleMiddleware::log($debugBar->getCollector('messages'), $formatter)); // Also log to the default PSR logger. if ($this->app->bound(LoggerInterface::class)) { $logger = $this->app->make(LoggerInterface::class); // Don't log to the same logger twice. if ($logger === $debugBar->getCollector('messages')) { return; } // Push the middleware on the stack. $stack->unshift(GuzzleMiddleware::log($logger, $formatter)); } }); }
/** * Get the client for making calls * * @return Client */ public function getHttpClient() { if ($this->client == null) { $handler = HandlerStack::create(); if ($this->mode == 'record') { $history = Middleware::history($this->callList); $handler->push($history); } elseif ($this->mode == 'playback') { $recordings = $this->getRecordings(); $playList = $recordings; $mockedResponses = []; foreach ($playList as $item) { $mockedResponses[] = new Response($item['statusCode'], $item['headers'], $item['body']); } $mockHandler = new MockHandler($mockedResponses); $handler = HandlerStack::create($mockHandler); } $this->client = new Client(['handler' => $handler]); if (!$this->shutdownRegistered) { register_shutdown_function(array($this, 'endRecord')); $this->shutdownRegistered = true; } } return $this->client; }
public function sync(array $subscriptions) { $synched = $failed = 0; if (!empty($subscriptions)) { $stack = HandlerStack::create(); $middleware = new Oauth1(['consumer_key' => $this->consumerKey, 'consumer_secret' => $this->consumerSecret, 'token' => '', 'token_secret' => '']); $stack->push($middleware); $client = new GuzzleClient(['base_uri' => 'https://restapi.mailplus.nl', 'handler' => $stack, 'auth' => 'oauth', 'headers' => ['Accept' => 'application/json', 'Content-Type' => 'application/json']]); foreach ($subscriptions as $subscription) { try { $contact = ['update' => true, 'purge' => false, 'contact' => ['externalId' => $subscription->getId(), 'properties' => ['email' => $subscription->getEmail()]]]; $response = $client->post('/integrationservice-1.1.0/contact', ['body' => json_encode($contact)]); if ($response->getStatusCode() == '204') { //Contact added successfully status code $this->subscriptionManager->updateStatus($subscription, Subscription::STATUS_SYNCED); ++$synched; } else { $this->subscriptionManager->updateStatus($subscription, Subscription::STATUS_FAILED); ++$failed; } } catch (\Exception $e) { $this->subscriptionManager->updateStatus($subscription, Subscription::STATUS_FAILED); ++$failed; } } } return sprintf('Synched %d,failed %d subscriptions of %d total', $synched, $failed, count($subscriptions)); }
protected function setUp() { // Create a mock and queue response $mock = new MockHandler([new Response(200, ['success' => 'true']), new RequestException("Error Communicating with Server", new Request('GET', 'test'))]); $handler = HandlerStack::create($mock); $this->client = new Client(['handler' => $handler]); }
private function apiWithResponse($status, $header, $body) { $responses = [new Response($status, $header, $body)]; $this->mockHandler = new MockHandler($responses); $client = new Client(['handler' => HandlerStack::create($this->mockHandler)]); return new API('en', '', $client); }
public function testDetailArray() { $mock = new MockHandler([new Response(200, ['Content-Type' => 'application/json'], '{ "id": "main", "authorizedFor": "Myself", "creator": { "id": "1234", "description": "*****@*****.**" }, "created": "2016-01-31 00:13:30", "#data": "KBC::ComponentProjectEncrypted==F2LdyHQB45lJHtf", "oauthVersion": "2.0", "appKey": "1234", "#appSecret": "KBC::ComponentEncrypted==/5fEM59+3+59+5+" }')]); // Add the history middleware to the handler stack. $container = []; $history = Middleware::history($container); $stack = HandlerStack::create($mock); $stack->push($history); $cred = new Credentials('some-token', ['handler' => $stack, 'url' => 'https://syrup.keboola.com/oauth-v2/']); $cred->enableReturnArrays(true); $result = $cred->getDetail('wr-dropbox', 'credentials-id'); $this->assertInternalType('array', $result); $this->assertCount(8, $result); $this->assertArrayHasKey('#data', $result); $this->assertArrayHasKey('#appSecret', $result); /** @var Request $request */ $request = $container[0]['request']; $this->assertEquals("https://syrup.keboola.com/oauth-v2/credentials/wr-dropbox/credentials-id", $request->getUri()->__toString()); $this->assertEquals("GET", $request->getMethod()); $this->assertEquals("some-token", $request->getHeader("x-storageapi-token")[0]); }
/** * @return GuzzleClient */ public function buildHttpMockClient($body) { // Create a mock and queue two responses. $mock = new MockHandler([new Response(200, array(), $body), new Response(200, array(), $body), new Response(400, array(), 'fault{'), new Response(400, array(), $body), new Response(400, array(), $body)]); $handler = HandlerStack::create($mock); return new GuzzleClient(['handler' => $handler]); }
/** * Create the Stack and set a default handler */ public function __construct() { if (!self::$stack) { self::$stack = HandlerStack::create(); self::$stack->setHandler(\GuzzleHttp\choose_handler()); } }
public function __construct($authKeys = array()) { $opts = array("headers" => array("User-Agent" => "twitter-wrapi"), "query" => array("stringify_ids" => "true"), 'auth' => 'oauth'); $handler = HandlerStack::create(); $handler->push(new Oauth1($authKeys)); function build(&$obj, $prefix, $apiList) { $path = $prefix; if ($prefix !== '') { $path .= '/'; } foreach ($apiList as $name) { $json = file_get_contents(__DIR__ . '/api/' . $path . $name . '.json'); $endpoint = json_decode($json, true); $pre = $prefix === '' ? $name : $prefix . '.' . $name; foreach ($endpoint as $sub => $ep) { $obj[$pre . '.' . $sub] = $ep; } } } $all = []; build($all, '', ['statuses', 'media', 'direct_messages', 'search', 'friendships', 'friends', 'followers', 'account', 'blocks', 'users', 'favorites', 'lists', 'saved_searches', 'geo', 'trends', 'application', 'help']); build($all, 'users', ['suggestions']); build($all, 'lists', ['members', 'subscribers']); parent::__construct('https://api.twitter.com/1.1/', $all, $opts, ['handler' => $handler]); }
public function __construct($email, $password, SessionStorageInterface $sessionStorage = null, $env = 'prod', $debug = false) { if (!in_array($env, ['test', 'prod'], true)) { throw new InvalidArgumentException("Environment must be one of: prod, test"); } if (null === $sessionStorage) { if (php_sapi_name() == "cli") { $sessionStorage = new MemorySessionStorage(); } else { $sessionStorage = new NativeSessionStorage(); } } $this->sessionStorage = $sessionStorage; $this->email = $email; $this->password = $password; $params = ['base_uri' => $this->{$env . 'Url'}]; if ($debug) { $this->transactionHistory = []; $history = Middleware::history($this->transactionHistory); $stack = HandlerStack::create(); $stack->push($history); $params['handler'] = $stack; } $this->client = new Client($params); }
/** * @param string $id * @param string $secret * @param string $url */ public function __construct($id, $secret, $url) { $this->logger = new NullLogger(); if (!strlen($id) || !strlen($secret)) { throw new InvalidArgumentException('api_id and api_secret must both be provided'); } $validatedUrl = filter_var($url, FILTER_VALIDATE_URL); if (!$validatedUrl) { throw new InvalidArgumentException($url . ' is not a valid URL'); } $this->id = $id; $this->secret = $secret; $this->baseUrl = $validatedUrl . '/page/api/'; $handlerStack = HandlerStack::create(GuzzleHttp\choose_handler()); $handlerStack->push(Middleware::mapRequest(function (RequestInterface $request) { $uri = $request->getUri(); $query = new Query($uri->getQuery()); /* * Add id and version to the query */ $query = $query->merge(Query::createFromArray(['api_id' => $this->id, 'api_ver' => '2'])); /* * Add timestamp to the query */ if (!$query->hasKey('api_ts')) { $query = $query->merge(Query::createFromArray(['api_ts', time()])); } $query = $query->merge(Query::createFromArray(['api_mac' => $this->generateMac($uri->getPath(), $query)])); return $request->withUri($uri->withQuery((string) $query)); })); $this->guzzleClient = new GuzzleClient(['handler' => $handlerStack]); }
public static function setUpBeforeClass() { $mock = new MockHandler([new Response(200, ['X-WP-Total' => 2, 'X-WP-TotalPages' => 1], json_encode(['posts' => []])), new RequestException('Error Communicating with Server', new Request('GET', 'test'))]); $handler = HandlerStack::create($mock); $client = new Client(['handler' => $handler]); self::$wp = new WpApi('http://test.dev/wp-api', $client); }