Exemple #1
0
 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]);
 }
 private function performTestRequest($logger, $request, $response)
 {
     $stack = new HandlerStack(new MockHandler([$response]));
     $stack->push(LoggingMiddleware::forLogger($logger));
     $handler = $stack->resolve();
     return $handler($request, [])->wait();
 }
 /**
  * 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 static function withDoctrineCache(Cache $doctrineCache)
 {
     $stack = new HandlerStack(new CurlMultiHandler());
     $stack->push(new CacheMiddleware(new PublicCacheStrategy(new DoctrineCacheStorage($doctrineCache))), 'cache');
     $client = new Client(['handler' => $stack]);
     return new self($client);
 }
 /**
  * Configures the stack using services tagged as http_client_middleware.
  *
  * @param \GuzzleHttp\HandlerStack $handler_stack
  *   The handler stack
  */
 public function configure(HandlerStack $handler_stack)
 {
     $this->initializeMiddlewares();
     foreach ($this->middlewares as $middleware_id => $middleware) {
         $handler_stack->push($middleware, $middleware_id);
     }
 }
Exemple #6
0
 /**
  * @dataProvider requestList
  */
 public function testQueueLimitsNumberOfProcessingRequests(array $queueData, $expectedDuration, $throttleLimit, $threshold = 0.05)
 {
     $handler = new HandlerStack(new LoopHandler());
     $handler->push(ThrottleMiddleware::create());
     $client = new \GuzzleHttp\Client(['handler' => $handler, 'base_uri' => Server::$url, 'timeout' => 10]);
     $queueEnd = $promises = $responses = $expectedStart = [];
     Server::start();
     Server::enqueue(array_fill(0, count($queueData), new Response()));
     foreach ($queueData as $queueItem) {
         list($queueId, $requestDuration, $expectedStartTime) = $queueItem;
         $options = [RequestOptions::HTTP_ERRORS => false, RequestOptions::HEADERS => ['duration' => $requestDuration], 'throttle_id' => $queueId, 'throttle_limit' => $throttleLimit];
         $expectedStart[$queueId] = $expectedStartTime;
         $promises[] = $client->getAsync('', $options)->then(function () use($queueId, &$queueStart, &$queueEnd) {
             if (!isset($queueStart[$queueId])) {
                 $queueStart[$queueId] = microtime(true);
             }
             $queueEnd[$queueId] = microtime(true);
         });
     }
     $start = microtime(true);
     $GLOBALS['s'] = microtime(1);
     \GuzzleHttp\Promise\all($promises)->wait();
     $duration = microtime(true) - $start;
     $this->assertGreaterThan($expectedDuration - $threshold, $duration);
     $this->assertLessThan($expectedDuration + $threshold, $duration);
     foreach ($queueEnd as $i => $endedAt) {
         $duration = $endedAt - $start;
         //            $this->assertGreaterThan($expectedDuration - $threshold, $endedAt - $start, "Queue #$i started too soon");
         //            $this->assertLessThan($queueInfo->getExpectedDuration() + $threshold, $queueInfo->getDuration(), "Queue #$i started too late");
         //
         //            $this->assertGreaterThan($started + $queueInfo->getExpectedDelay() - $threshold, $queueInfo->getStartedAt(), "Queue #$i popped too early");
         //            $this->assertLessThan($started + $queueInfo->getExpectedDelay() + $threshold, $queueInfo->getStartedAt(), "Queue #$i popped too late");
     }
 }
Exemple #7
0
 /**
  * Build the guzzle client instance.
  *
  * @param array $config Additional configuration
  *
  * @return GuzzleClient
  */
 private static function buildClient(array $config = [])
 {
     $handlerStack = new HandlerStack(\GuzzleHttp\choose_handler());
     $handlerStack->push(Middleware::prepareBody(), 'prepare_body');
     $config = array_merge(['handler' => $handlerStack], $config);
     return new GuzzleClient($config);
 }
 /**
  * @param ClientInterface|null $client
  */
 public function __construct(ClientInterface $client = null)
 {
     if (!$client) {
         $handlerStack = new HandlerStack(\GuzzleHttp\choose_handler());
         $handlerStack->push(Middleware::prepareBody(), 'prepare_body');
         $client = new Client(['handler' => $handlerStack]);
     }
     $this->client = $client;
 }
 /**
  * @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 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]);
 }
 public function testAddLogger()
 {
     $logger = new Logger('Logger');
     $messageFormatter = new MessageFormatter();
     $logLevel = LogLevel::ALERT;
     $middlewareCallback = function () {
     };
     $this->httpMock->expects($this->once())->method('createMiddlewareLogCallback')->with($logger, $messageFormatter, $logLevel)->willReturn($middlewareCallback);
     $this->handlerStackMock->expects($this->once())->method('push')->with($middlewareCallback, 'logger');
     $this->httpMock->addLogger($logger, $messageFormatter, $logLevel);
 }
Exemple #12
0
 /**
  * Getter for the HTTP client.
  *
  * @return Client
  */
 protected function getHttpClient()
 {
     if ($this->client === null) {
         if ($this->logger instanceof LoggerInterface) {
             $this->handlerStack->push(Middleware::log($this->logger, $this->messageFormatter, $this->logLevel));
         }
         $this->options['handler'] = $this->handlerStack;
         $this->client = new Client($this->options);
     }
     return $this->client;
 }
Exemple #13
0
 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]);
 }
Exemple #14
0
 /**
  * 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);
 }
Exemple #15
0
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 testSubscriberDoesNotDoAnythingForNonGigyaAuthRequests()
 {
     $handler = new MockHandler([function (RequestInterface $request) {
         $query = $request->getUri()->getQuery();
         $this->assertNotRegExp('/client_id=/', $query);
         $this->assertNotRegExp('/client_secret=/', $query);
         return new Response(200);
     }]);
     $stack = new HandlerStack($handler);
     $stack->push(CredentialsAuthMiddleware::middleware('key', 'secret', 'user'));
     $comp = $stack->resolve();
     $promise = $comp(new Request('GET', 'https://example.com'), ['auth' => 'oauth']);
     $this->assertInstanceOf(PromiseInterface::class, $promise);
 }
 /**
  * @dataProvider expectProvider
  *
  * @param int $duration The expected duration.
  */
 public function testNullStopwatch($duration)
 {
     // HandlerStack
     $response = new Response(200);
     $stack = new HandlerStack(new MockHandler([$response]));
     // Middleware
     $middleware = new StopwatchMiddleware();
     $stack->push($middleware);
     $handler = $stack->resolve();
     // Request
     $request = new Request('GET', 'http://example.com');
     $promise = $handler($request, []);
     $response = $promise->wait();
     $this->assertNotEquals($response->getHeaderLine('X-Duration'), $duration);
 }
Exemple #18
0
 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);
 }
Exemple #19
0
 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]);
 }
Exemple #20
0
 private function getMockClient(array $response)
 {
     $mock = new MockHandler($response);
     $handler = HandlerStack::create($mock);
     $client = new Client(['handler' => $handler]);
     return $client;
 }
Exemple #21
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]);
 }
 /**
  *
  * @return Client
  */
 protected function getClient(array $responseQueue = [])
 {
     $mock = new MockHandler($responseQueue);
     $handler = HandlerStack::create($mock);
     $client = new Client(['handler' => $handler]);
     return $client;
 }
Exemple #23
0
 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);
 }
 /**
  * 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);
 }
 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));
 }
Exemple #26
0
 /**
  * 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);
 }
 /**
  * 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));
         }
     });
 }
 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());
 }
 /**
  * @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]);
 }
Exemple #30
0
 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);
 }