/** * 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() { static::init(); $Stack = new HandlerStack(); $Stack->setHandler(new CurlHandler()); /** * Здесь ставим ловушку, чтобы с помощью редиректов * определить адрес сервера, который сможет отсылать сообщения */ $Stack->push(Middleware::mapResponse(function (ResponseInterface $Response) { $code = $Response->getStatusCode(); if ($code >= 301 && $code <= 303 || $code == 307 || $code == 308) { $location = $Response->getHeader('Location'); preg_match('/https?://([^-]*-)client-s/', $location, $matches); if (array_key_exists(1, $matches)) { $this->cloud = $matches[1]; } } return $Response; })); /** * Ловушка для отлова хедера Set-RegistrationToken * Тоже нужен для отправки сообщений */ $Stack->push(Middleware::mapResponse(function (ResponseInterface $Response) { $header = $Response->getHeader("Set-RegistrationToken"); if (count($header) > 0) { $this->regToken = trim(explode(';', $header[0])[0]); } return $Response; })); //$cookieJar = new FileCookieJar('cookie.txt', true); $this->client = new Client(['handler' => $Stack, 'cookies' => true]); }
public function setUp() { $this->context = new Context(['keys' => ['pda' => 'secret'], 'algorithm' => 'hmac-sha256', 'headers' => ['(request-target)', 'date']]); $stack = new HandlerStack(); $stack->setHandler(new MockHandler([new Response(200, ['Content-Length' => 0])])); $stack->push(GuzzleHttpSignatures::middlewareFromContext($this->context)); $stack->push(Middleware::history($this->history)); $this->client = new Client(['handler' => $stack]); }
/** * @expectedException \GuzzleTor\TorNewIdentityException */ public function testExceptionWhileNewIdentity() { $stack = new HandlerStack(); $stack->setHandler(new CurlHandler()); $stack->push(Middleware::tor('127.0.0.1:9050', 'not-existed-host:9051')); $client = new Client(['handler' => $stack]); // Throw TorNewIdentityException because of wrong tor control host $client->get('https://check.torproject.org/', ['tor_new_identity' => true, 'tor_new_identity_exception' => true]); }
public function __construct($bucket, $pub_key, $sec_key, $suffix = '.ufile.ucloud.cn', $https = false, $debug = false) { $this->bucket = $bucket; $this->pub_key = $pub_key; $this->sec_key = $sec_key; $this->host = ($https ? 'https://' : 'http://') . $bucket . $suffix; $stack = new HandlerStack(); $stack->setHandler(new CurlHandler()); $stack->push(static::auth($bucket, $pub_key, $sec_key)); $this->httpClient = new Client(['base_uri' => $this->host, 'handler' => $stack, 'debug' => $debug]); }
/** * HttpClient constructor. * * @param string $key * @param string $secret * @param array $options */ public function __construct($key, $secret, array $options = []) { $options = array_merge($this->options, $options); $stack = new HandlerStack(); $stack->setHandler(new CurlHandler()); $stack->push(Middleware::mapRequest(function (RequestInterface $request) use($key, $secret, $options) { $date = new \DateTime('now', new \DateTimeZone('UTC')); return $request->withHeader('User-Agent', $options['user_agent'])->withHeader('Apikey', $key)->withHeader('Date', $date->format('Y-m-d H:i:s'))->withHeader('Signature', sha1($secret . $date->format('Y-m-d H:i:s'))); })); $this->options = array_merge($this->options, $options, ['handler' => $stack]); $this->options['base_uri'] = sprintf($this->options['base_uri'], $this->options['api_version']); $this->client = new Client($this->options); }
function get_tor_ip() { $stack = new HandlerStack(); $stack->setHandler(new CurlHandler()); $stack->push(Middleware::tor()); $client = new Client(['handler' => $stack]); $response = $client->get('https://check.torproject.org/'); if (preg_match('/<strong>([\\d.]+)<\\/strong>/', $response->getBody(), $matches)) { return $matches[1]; } else { return null; } }
public function testRegisterPlugin() { $middleware = $this->getMiddleware(); $container = []; $history = Middleware::history($container); $stack = new HandlerStack(); $stack->setHandler(new MockHandler([new Response(200)])); $stack->push($middleware); $stack->push($history); $client = new Client(['base_url' => 'http://example.com', 'handler' => $stack]); $client->get('/resource/1'); $transaction = reset($container); $request = $transaction['request']; $authorization = $request->getHeaderLine('Authorization'); $this->assertRegExp('@Acquia 1:([a-zA-Z0-9+/]+={0,2})$@', $authorization); }
private function register() { $this->container->add('WpsClient', function () { $stack = new HandlerStack(); $stack->setHandler(new CurlHandler()); $stack->push(Middleware::mapRequest(function (RequestInterface $request) { //print_r((string)$request->getUri() . PHP_EOL); return $request; })); return WpsClient::factory(['handler' => $stack, 'base_uri' => $this->config['base_uri'], 'auth' => $this->config['auth'], 'headers' => ['Content-Type' => 'application/json']]); }); $this->container->add('RequestBuilder', function ($args) { $client = $this->container->get('WpsClient'); $uriGenerator = new UriGenerator(); return new RequestBuilder($client, $uriGenerator, $args); }); }
/** * @param string $apiKey * @param string $secret * @param string $url * @param ClientInterface|null $client * @param BucketManager $bucketManager * @param FileManager $fileManager * @param array $connectionConfig */ public function __construct($apiKey, $secret, $url = 'https://myracloud-upload.local/v2/', ClientInterface $client = null, BucketManager $bucketManager = null, FileManager $fileManager = null, array $connectionConfig = []) { $this->apiKey = $apiKey; $this->secret = $secret; $this->url = $url; if ($client === null) { $stack = new HandlerStack(); $stack->setHandler(new CurlHandler()); $stack->push(Middleware::prepareBody()); $stack->push(Middleware::mapRequest(function (RequestInterface $request) use($secret, $apiKey) { return $request->withHeader('Authorization', "MYRA {$apiKey}:" . new Authentication\Signature($request->getMethod(), $request->getRequestTarget(), $secret, $request->getHeaders(), $request->getBody())); })); $client = new Client(array_merge(['base_uri' => $this->url, 'handler' => $stack], $connectionConfig)); } $this->client = $client; $this->bucketManager = $bucketManager ?: new BucketManager($this->client); $this->fileManager = $fileManager ?: new FileManager($this->client); }
public function makeStack(CurlHandler $curl, HandlerStack $stack) { $stack->setHandler($curl); $stack->push(function (callable $handler) { return function (RequestInterface $request, array $options) use($handler) { $method = $request->getMethod(); $uri = '/' . trim($request->getUri()->getPath(), '/'); $qs = $request->getUri()->getQuery(); if ($qs) { $qs = '?' . $qs; } $header = $this->getAuthenticationHeader($method, $uri); $request = $request->withHeader('Authentication', $header); $request = $request->withUri(Psr7\uri_for(static::BASE_URL . $uri . $qs)); return $handler($request, $options); }; }); return $stack; }
public function testIntegrationResponseHandler() { $options = $this->getOptions(); $options->setDatabase("mydb"); $client = $this->getClient(); $client->createDatabase("mydb"); $client->mark(["time" => "2015-09-10T23:20:35Z", "points" => [["measurement" => "cpu", "fields" => ["value" => "OK", "hello" => 2]], ["measurement" => "mem", "fields" => ["value" => "KO", "hello" => 4]]]]); $stack = new HandlerStack(); $stack->setHandler(new CurlHandler()); $stack->push(\InfluxDB\Handler\message_handler()); // Push the response handler $http = new HttpClient(['handler' => $stack]); $options = new Http\Options(); $options->setDatabase("mydb"); $reader = new Http\Reader($http, $options); $writer = new Http\Writer($http, $options); $client = new Client($reader, $writer); $response = $client->query("SELECT * FROM cpu,mem"); $this->assertEquals(["cpu" => [["value" => "OK", "hello" => 2, "time" => "2015-09-10T23:20:35Z"]], "mem" => [["value" => "KO", "hello" => 4, "time" => "2015-09-10T23:20:35Z"]]], $response); }
/** * @return HandlerStack */ protected function buildGuzzleStack() { // New stack $stack = new HandlerStack(); // Set handler for the stack, let Guzzle choose $stack->setHandler(\GuzzleHttp\choose_handler()); // Add Request middleware to the stack that logs the url $stack->push(Middleware::mapRequest($this->buildMiddlewareLogRequestUrl())); // Return return $stack; }
/** * Creates a HandlerStack based off of the supplied configuration. * * @param string $handlerClass full class name to use for the HTTP handler implementation * @return HandlerStack configured HandlerStack implementation */ protected function buildHandlerStack($handlerClass) { $stack = new HandlerStack(); $stack->setHandler(new $handlerClass()); $stack->push(Middleware::mapRequest(function (RequestInterface $request) { $timestamp = gmdate('r'); $authorization = $this->getAuthorization($timestamp); $requestInterface = $request->withHeader('Date', $timestamp)->withHeader('x-request-id', (string) Uuid::uuid4()); if (!$this->noAuth) { $requestInterface = $requestInterface->withHeader('Authorization', $authorization); } return $requestInterface; })); $decider = function ($retries, Request $request, Response $response = null, RequestException $exception = null) { // Stop retrying if we have exceeded our max if ($retries > $this->retries) { return false; } // Retry connection exceptions if ($exception instanceof ConnectException) { return true; } if ($response) { // Retry on server errors if ($response->getStatusCode() >= 500) { return true; } } return false; }; if ($this->retries > 0) { $stack->push(Middleware::retry($decider)); } return $stack; }
/** * Build a handler. * * @return HandlerStack */ protected function getHandler() { $stack = new HandlerStack(); $stack->setHandler(new CurlHandler()); foreach ($this->middlewares as $middleware) { $stack->push($middleware); } return $stack; }
/** * Returns a Guzzle client with appropriate headers set for requests. * * @return GuzzleHttpClient */ protected function getGuzzleClient() { $headerMiddleware = function (RequestInterface $request) { return $request->withHeader('Authorization', 'Bearer ' . $this->getApiKey())->withHeader('Content-type', 'text/json'); }; $headerMiddleware->bindTo($this); $stack = new HandlerStack(); $stack->setHandler(new CurlHandler()); $stack->push(Middleware::mapRequest($headerMiddleware)); $client = new GuzzleHttpClient(['base_uri' => self::BASE_URL, 'handler' => $stack]); return $client; }
/** * Generate a new handler that will manage the HTTP requests. * * Some middleware are also configured to manage the authorization header and request URI * * @param string $authorization Authorization code to pass in the header * @return \GuzzleHttp\HandlerStack */ private function setHandler($authorization) { $stack = new HandlerStack(); $stack->setHandler(new CurlHandler()); // Set authorization headers $this->authorization = $authorization; $stack->push(Middleware::mapRequest(function (Request $request) { return $request->withHeader('Authorization', $this->authorization); }), 'set_authorization_header'); // Set the request ui $stack->push(Middleware::mapRequest(function (Request $request) { $uri = $request->getUri()->withHost($this->host)->withScheme($this->scheme); return $request->withUri($uri); }), 'set_host'); return $stack; }
/** * Construct a FamilySearch Client. * * @param array $options A keyed array of configuration options for the client. Available options: * * * `clientId` - Required for authentication. * * `redirectURI` - Required for authentication. * * `accessToken` - If the access token is set then the `clientId` and `redirectURI` are not needed. * * `environment` - `production`, `beta`, or `sandbox`; defaults to `sandbox`. * * `userAgent` - A string which will be prepended to the default user agent string. * * `pendingModifications` - An array of pending modifications that should be enabled. * * `logger` - A `Psr\Log\LoggerInterface`. A logger can also be registered via the `setLogger()` method but passing it in as an option during instantiation ensures that the logger will see all client events. * * `middleware` - An array of [Guzzle Middleware](http://docs.guzzlephp.org/en/latest/handlers-and-middleware.html#middleware). * * `httpExceptions` - When `true`, the client will throw a `Gedcomx\Rs\Client\Exception\GedcomxApplicationException` when a 400 or 500 level HTTP response is received. * * `throttling` - When `true`, the client will automatically handled throttled responses. */ public function __construct($options = array()) { if (isset($options['redirectURI'])) { $this->redirectURI = $options['redirectURI']; } if (isset($options['clientId'])) { $this->clientId = $options['clientId']; } // Set the proper homeURI based on the environment. // Default to sandbox. $environment = ''; $baseURI = ''; if (isset($options['environment'])) { $environment = $options['environment']; } switch ($environment) { case 'production': $baseURI = 'https://familysearch.org'; break; case 'beta': $baseURI = 'https://beta.familysearch.org'; break; default: $baseURI = 'https://sandbox.familysearch.org'; break; } $this->homeURI = $baseURI . '/platform/collection'; // Middleware $this->stack = new HandlerStack(); $this->stack->setHandler(new CurlHandler()); $this->stack->push(Middleware::httpErrors()); $this->stack->push(Middleware::redirect()); // Pending modifications if (isset($options['pendingModifications']) && is_array($options['pendingModifications']) && count($options['pendingModifications']) > 0) { $experiments = join(",", $options['pendingModifications']); $this->stack->push(Middleware::mapRequest(function (RequestInterface $request) use($experiments) { return $request->withHeader('X-FS-Feature-Tag', $experiments); })); } // Throttling if (isset($options['throttling']) && $options['throttling'] === true) { $this->stack->push(ThrottlingMiddleware::middleware()); } // Set user agent string $userAgent = 'gedcomx-php/1.1.1 ' . \GuzzleHttp\default_user_agent(); if (isset($options['userAgent'])) { $userAgent = $options['userAgent'] . ' ' . $userAgent; } // Custom middleware if (isset($options['middleware']) && is_array($options['middleware'])) { foreach ($options['middleware'] as $middleware) { $this->stack->push($middleware); } } // This goes last so that it sees the final request and response if (isset($options['logger'])) { $this->setLogger($options['logger']); } $clientOptions = ['handler' => $this->stack, 'base_uri' => $baseURI, 'headers' => ['User-Agent' => $userAgent]]; // Throw exceptions if (isset($options['httpExceptions']) && $options['httpExceptions'] === true) { $clientOptions['http_errors'] = true; } else { $clientOptions['http_errors'] = false; } // Create client $this->client = new Client($clientOptions); $this->stateFactory = new FamilyTreeStateFactory(); $this->createHomeState(); $this->createTreeState(); if (isset($options['accessToken'])) { $this->treeState->authenticateWithAccessToken($options['accessToken']); } }
private function buildClientAndRequest() { $this->logger->info("Getting Request Client"); $stack = new HandlerStack(); $stack->setHandler(new CurlHandler()); $stack->push(Middleware::mapRequest(function (RequestInterface $request) { return $this->addRequestHeaders($request); })); $stack->push(Middleware::mapResponse(function (ResponseInterface $response) { $this->logger->info('Response status code: ' . $response->getStatusCode()); $this->validateResponse($response); return $response; })); $this->client = new Client(['handler' => $stack, 'base_uri' => $this->baseAddress, 'verify' => false]); $this->logger->info("Request URI : " . $this->mozuUrl->getUrl()); $this->request = new Psr7\Request($this->mozuUrl->getVerb(), $this->mozuUrl->getUrl(), array(), $this->requestBody); }
/** * Ensures the HTTP HMAC middleware registers correctly. */ public function testRegisterPlugin() { $realm = 'Pipet service'; $requestHeaders = ['X-Authorization-Timestamp' => '1432075982']; $request = new Request('GET', 'https://example.acquiapipet.net/v1.0/task-status/133?limit=10', $requestHeaders); $authHeaderBuilder = new AuthorizationHeaderBuilder($request, $this->authKey); $authHeaderBuilder->setRealm($realm); $authHeaderBuilder->setId('efdde334-fe7b-11e4-a322-1697f925ec7b'); $authHeaderBuilder->setNonce('d1954337-5319-4821-8427-115542e08d10'); $authHeader = $authHeaderBuilder->getAuthorizationHeader(); $middleware = new MockHmacAuthMiddleware($this->authKey, $realm, [], $authHeader); $container = []; $history = Middleware::history($container); $responseHeaders = ['X-Server-Authorization-HMAC-SHA256' => 'LusIUHmqt9NOALrQ4N4MtXZEFE03MjcDjziK+vVqhvQ=']; $response = new Response(200, $responseHeaders); $stack = new HandlerStack(); $stack->setHandler(new MockHandler([$response])); $stack->push($middleware); $stack->push($history); $client = new Client(['base_uri' => 'https://example.acquiapipet.net/', 'handler' => $stack]); $client->send($request); $transaction = reset($container); $request = $transaction['request']; $expected = 'acquia-http-hmac realm="Pipet%20service",' . 'id="efdde334-fe7b-11e4-a322-1697f925ec7b",' . 'nonce="d1954337-5319-4821-8427-115542e08d10",' . 'version="2.0",' . 'headers="",' . 'signature="MRlPr/Z1WQY2sMthcaEqETRMw4gPYXlPcTpaLWS2gcc="'; $this->assertEquals($expected, $request->getHeaderLine('Authorization')); }
public function testCanAddAfterByName() { $meths = $this->getFunctions(); $builder = new HandlerStack(); $builder->setHandler($meths[1]); $builder->push($meths[2], 'a'); $builder->push($meths[3], 'b'); $builder->after('a', $meths[4], 'c'); $builder->after('b', $meths[4], 'd'); $lines = explode("\n", (string) $builder); $this->assertContains('4) Name: \'a\'', $lines[0]); $this->assertContains('3) Name: \'c\'', $lines[1]); $this->assertContains('2) Name: \'b\'', $lines[2]); $this->assertContains('1) Name: \'d\'', $lines[3]); }