Пример #1
0
 /**
  * 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;
 }
Пример #2
0
 /**
  * @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]);
 }
Пример #3
0
 public function testSSO()
 {
     $pid = Helper::getSomeProject();
     $user = Helper::getSomeUser();
     Helper::getClient()->getProjects()->addUser($pid, $user['uid']);
     $targetUrl = "/#s=/gdc/projects/{$pid}|projectDashboardPage";
     $sso = new SSO(null, null, KBGDC_API_URL);
     $ssoLink = $sso->getUrl(KBGDC_USERNAME, KBGDC_SSO_KEY, KBGDC_SSO_PROVIDER, $targetUrl, $user['email'], 3600, KBGDC_SSO_KEY_PASS);
     $stack = \GuzzleHttp\HandlerStack::create();
     $lastRequest = null;
     $stack->push(\GuzzleHttp\Middleware::mapRequest(function (Request $request) use(&$lastRequest) {
         $lastRequest = $request;
         return $request;
     }));
     $client = new Client(['handler' => $stack, \GuzzleHttp\RequestOptions::ALLOW_REDIRECTS => true, 'verify' => false]);
     try {
         $client->request('GET', $ssoLink, ['headers' => ['Accept' => 'application/json']]);
     } catch (RequestException $e) {
         if ($e->hasResponse()) {
             $response = $e->getResponse()->getBody();
             $this->fail("{$response} on link: {$ssoLink}");
         } else {
             $this->fail($e->getMessage() . " on link: {$ssoLink}");
         }
     }
     /** @var Request $lastRequest */
     $result = $lastRequest->getUri()->__toString();
     $this->assertStringEndsWith($targetUrl, urldecode($result));
 }
 public function notifyWhenResponseIsComplete()
 {
     parent::$stack->push(Middleware::mapResponse(function (ResponseInterface $response) {
         print 'Response!' . PHP_EOL;
         return $response;
     }));
 }
 public function post($full_url, array $multi_parts = [], array $headers = [])
 {
     $options = ['debug' => GUZZLE_DEBUG];
     // Grab the client's handler instance.
     $clientHandler = $this->client->getConfig('handler');
     // Create a middleware that echoes parts of the request.
     $tapMiddleware = Middleware::tap(function ($request) {
         echo $request->getHeader('Content-Type');
         // application/json
         echo $request->getBody();
         // {"foo":"bar"}
     });
     //$options['handler'] = $tapMiddleware($clientHandler);
     $multi_part_vars = array();
     foreach ($multi_parts as $name => $data) {
         if (is_array($data)) {
             $data['name'] = $name;
         } else {
             $data = ['name' => $name, 'contents' => $data];
         }
         $multi_part_vars[] = $data;
     }
     $options['multipart'] = $multi_part_vars;
     //$options['headers'] = ['Referer' =>  $full_url];
     if (!empty($headers)) {
         $options['headers'] = $headers;
     }
     $this->response = $this->client->post($full_url, $options);
     return $this;
 }
Пример #6
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]);
 }
Пример #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);
 }
Пример #8
0
 /**
  * Test validation of Cas tickets.
  *
  * @covers ::__construct
  * @covers ::validateTicket
  * @covers ::validateVersion1
  * @covers ::validateVersion2
  * @covers ::verifyProxyChain
  * @covers ::parseAllowedProxyChains
  * @covers ::parseServerProxyChain
  *
  * @dataProvider validateTicketDataProvider
  */
 public function testValidateTicket($version, $ticket, $username, $response, $is_proxy, $can_be_proxied, $proxy_chains, $ssl_verification)
 {
     $mock = new MockHandler([new Response(200, array(), $response)]);
     $handler = HandlerStack::create($mock);
     $container = [];
     $history = Middleware::history($container);
     $handler->push($history);
     $httpClient = new Client(['handler' => $handler]);
     $casHelper = $this->getMockBuilder('\\Drupal\\cas\\Service\\CasHelper')->disableOriginalConstructor()->getMock();
     $casValidator = new CasValidator($httpClient, $casHelper);
     $casHelper->expects($this->any())->method('getCasProtocolVersion')->will($this->returnValue($version));
     $casHelper->expects($this->once())->method('getSslVerificationMethod')->willReturn($ssl_verification);
     $casHelper->expects($this->any())->method('getCertificateAuthorityPem')->will($this->returnValue('foo'));
     $casHelper->expects($this->any())->method('isProxy')->will($this->returnValue($is_proxy));
     $casHelper->expects($this->any())->method('canBeProxied')->will($this->returnValue($can_be_proxied));
     $casHelper->expects($this->any())->method('getProxyChains')->will($this->returnValue($proxy_chains));
     $property_bag = $casValidator->validateTicket($version, $ticket, array());
     // Test that we sent the correct ssl option to the http client.
     foreach ($container as $transaction) {
         switch ($ssl_verification) {
             case CasHelper::CA_CUSTOM:
                 $this->assertEquals('foo', $transaction['options']['verify']);
                 break;
             case CasHelper::CA_NONE:
                 $this->assertEquals(FALSE, $transaction['options']['verify']);
                 break;
             default:
                 $this->assertEquals(TRUE, $transaction['options']['verify']);
         }
     }
     $this->assertEquals($username, $property_bag->getUsername());
 }
Пример #9
0
 /**
  * Execute the job.
  *
  * @return void
  */
 public function handle()
 {
     $config = app('Illuminate\\Contracts\\Config\\Repository');
     $client = app(Client::class);
     $logging = $config->get('captain_hook.log.active') && $config->get('queue.driver') != 'sync';
     foreach ($this->webhooks as $webhook) {
         if ($logging) {
             if ($config->get('captain_hook.log.storage_quantity') != -1 && $webhook->logs()->count() >= $config->get('captain_hook.log.storage_quantity')) {
                 $webhook->logs()->orderBy('updated_at', 'desc')->first()->delete();
             }
             $log = new WebhookLog(['webhook_id' => $webhook['id'], 'url' => $webhook['url']]);
             $middleware = Middleware::tap(function (RequestInterface $request, $options) use($log) {
                 $log->payload_format = isset($request->getHeader('Content-Type')[0]) ? $request->getHeader('Content-Type')[0] : null;
                 $log->payload = $request->getBody()->getContents();
             }, function ($request, $options, Promise $response) use($log) {
                 $response->then(function (ResponseInterface $response) use($log) {
                     $log->status = $response->getStatusCode();
                     $log->response = $response->getBody()->getContents();
                     $log->response_format = $log->payload_format = isset($response->getHeader('Content-Type')[0]) ? $response->getHeader('Content-Type')[0] : null;
                     $log->save();
                 });
             });
             $client->post($webhook['url'], ['body' => $this->eventData, 'handler' => $middleware($client->getConfig('handler'))]);
         } else {
             $client->postAsync($webhook['url'], ['body' => $this->eventData, 'verify' => false, 'future' => true]);
         }
     }
 }
Пример #10
0
 /**
  * @covers ::send
  * @covers ::buildRequest
  * @covers ::getGzippedBody
  * @covers ::getAuthorization
  */
 public function testSend()
 {
     $container = array();
     $history = Middleware::history($container);
     $mockHandler = new MockHandler(array(new Response(200, array(), 'Everything OK')));
     $stack = HandlerStack::create($mockHandler);
     $stack->push($history);
     // $stack->push($mockHandler);
     $http = new GuzzleAdapter(new GuzzleClient(array('handler' => $stack)));
     $client = new Client('aaaaa', 'bbbbb', $http);
     $message = new Message('http://www.example.com/', $client);
     $message->set('foo', 'bar');
     // Call send() and ensure the right response was returned (which we set up above)
     $response = $message->send();
     $this->assertEquals(200, $response->getStatusCode());
     $this->assertEquals('Everything OK', $response->getBody());
     // Ensure the request has everything that should be there
     $this->assertCount(1, $container);
     $request = $container[0]['request'];
     $this->assertEquals('POST', $request->getMethod());
     $this->assertEquals('http://www.example.com/', (string) $request->getUri());
     $this->assertEquals('gzip', $request->getHeaderLine('Content-Encoding'));
     $this->assertEquals('application/json', $request->getHeaderLine('Content-Type'));
     $this->assertEquals('2Isi0VhuV8oniANJzAZVBEZ3DSAKmP0hQrVh3jbUNaQ=', $request->getHeaderLine('Authorization'));
     $this->assertEquals('H4sIAAAAAAAAA6tWSsvPV7JSSkosUqoFAO/1K/4NAAAA', base64_encode((string) $request->getBody()));
 }
Пример #11
0
 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);
 }
Пример #12
0
 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]);
 }
Пример #13
0
 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
         }
     }
 }
 /**
  * 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));
         }
     });
 }
Пример #15
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);
 }
Пример #16
0
 public function getStackFunction()
 {
     return Middleware::mapRequest(function (RequestInterface $request) {
         // Notice that we have to return a request object
         return $request->withHeader('X-Vault-Token', $this->_token);
     });
 }
Пример #17
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);
 }
Пример #18
0
 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);
 }
 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]);
 }
 public function toApi(Request $request)
 {
     $client = new \GuzzleHttp\Client();
     $input = $request::all();
     $command = 'request';
     $api_key = 'MjuhMtfAAfvJqzbnWFLA';
     // $api_key = 'mysendykey';
     $api_username = '******';
     // $api_username = '******';
     $from_name = 'Chris Munialo';
     $from_lat = $input['lat'];
     $from_long = $input['lng'];
     $from_description = '';
     $to_name = 'TRM';
     $to_lat = $input['lat1'];
     $to_long = $input['lng1'];
     $to_description = '';
     $recepient_name = 'John';
     $recepient_phone = '0710000000';
     $recepient_email = '*****@*****.**';
     $pick_up_date = '2016-04-20 12:12:12';
     $status = false;
     $pay_method = 0;
     $amount = 10;
     $return = true;
     $note = 'Sample note';
     $note_status = true;
     $request_type = 'quote';
     $info = ['command' => $command, 'data' => ['api_key' => $api_key, 'api_username' => $api_username, 'from' => ['from_name' => $from_name, 'from_lat' => floatval($from_lat), 'from_long' => floatval($from_long), 'from_description' => $from_description], 'to' => ['to_name' => $to_name, 'to_lat' => floatval($to_lat), 'to_long' => floatval($to_long), 'to_description' => $to_description], 'recepient' => ['recepient_name' => $recepient_name, 'recepient_phone' => $recepient_phone, 'recepient_email' => $recepient_email], 'delivery_details' => ['pick_up_date' => $pick_up_date, 'collect_payment' => ['status' => $status, 'pay_method' => $pay_method, 'amount' => $amount], 'return' => $return, 'note' => $note, 'note_status' => $note_status, 'request_type' => $request_type]]];
     $clientHandler = $client->getConfig('handler');
     // Create a middleware that echoes parts of the request.
     $tapMiddleware = Middleware::tap(function ($request) {
         $request->getHeader('Content-Type');
         // application/json
         $request->getBody();
         // {"foo":"bar"}
     });
     $endpoint = 'https://developer.sendyit.com/v1/api/#request';
     // $info = json_encode($info);
     $client = new \GuzzleHttp\Client();
     $res = $client->request('POST', $endpoint, ['json' => $info, 'handler' => $tapMiddleware($clientHandler), 'headers' => ['Accept' => 'application/json']]);
     // $res->getStatusCode();
     // "200"
     // $res->getHeader('content-type');
     // 'application/json; charset=utf8'
     $pns = json_decode($res->getBody(), true);
     // var_dump($pns);
     // echo $pns;
     // echo $pns;
     // $pns= $res->getBody();
     // {"type":"User"...
     // Send an asynchronous request.
     // $request = new \GuzzleHttp\Psr7\Request('POST', $endpoint );
     // $promise = $client->sendAsync($request)->then(function ($response) {
     // $response->getBody();
     // });
     // $promise->wait();
     return view('orders.new', ['pns' => $pns]);
 }
Пример #21
0
 public static function buildMockedClient(array &$container, array $responses)
 {
     $history = Middleware::history($container);
     $mock = new MockHandler($responses);
     $handler = HandlerStack::create($mock);
     $handler->push($history);
     return new Client(['handler' => $handler]);
 }
Пример #22
0
 /**
  * testRetries500Errors.
  */
 public function testRetries500Errors()
 {
     $mock = new MockHandler([new Response(500), new Response(200)]);
     $handler = HandlerStack::create($mock);
     $handler->push(Middleware::retry(Backoff::decider(), Backoff::delay()));
     $client = new Client(['handler' => $handler]);
     $this->assertEquals(200, $client->request('GET', '/')->getStatusCode());
 }
Пример #23
0
 private function createAuthStack()
 {
     $stack = HandlerStack::create();
     $stack->push(Middleware::mapRequest(function (RequestInterface $request) {
         return $request->withHeader('Authorization', "Bearer " . $this->accessToken);
     }));
     return $stack;
 }
 /**
  * Get Guzzle with mock response and request history stored in container
  *
  * @param array $container
  * @param Response[] $responses
  * @return Client
  */
 public function getMockHttpClientWithHistoryAndResponses(&$container, $responses)
 {
     $mock = new MockHandler($responses);
     $stack = HandlerStack::create($mock);
     $history = Middleware::history($container);
     $stack->push($history);
     return new Client(['handler' => $stack]);
 }
 /**
  * @access private
  *
  * @param bool $delay default to true, can be false to speed up tests
  *
  * @return callable
  */
 public function retry($delay = true)
 {
     if ($delay) {
         return Middleware::retry($this->newRetryDecider(), $this->getRetryDelay());
     } else {
         return Middleware::retry($this->newRetryDecider());
     }
 }
Пример #26
0
 /**
  * @param null|string $response
  * @return GuzzleClient
  * @see ClientTest::getGuzzle()
  * @link https://github.com/FriendsOfPHP/Goutte/blob/master/Goutte/Tests/ClientTest.php
  */
 protected function getGuzzle($response)
 {
     $handlerStack = HandlerStack::create(new MockHandler([new GuzzleResponse(200, [], $response)]));
     $history = [];
     $handlerStack->push(Middleware::history($history));
     $guzzle = new GuzzleClient(['redirect.disable' => true, 'base_uri' => '', 'handler' => $handlerStack]);
     return $guzzle;
 }
 public function __construct($parameters = [], GuzzleHttp\ClientInterface $httpClient = null)
 {
     $this->configure($parameters);
     $stack = GuzzleHttp\HandlerStack::create();
     if ($this->logger instanceof LoggerInterface) {
         $stack->push(GuzzleHttp\Middleware::log($this->logger, new GuzzleHttp\MessageFormatter(GuzzleHttp\MessageFormatter::DEBUG)));
     }
     $this->httpClient = new GuzzleHttp\Client(['handler' => $stack]);
 }
 protected function setUp()
 {
     $mock = new MockHandler([new Response(200, ["X-Foo" => "Bar"], "It worked!")]);
     $stack = HandlerStack::create($mock);
     $history = Middleware::history($this->container);
     $stack->push($history);
     $client = new Client(["handler" => $stack]);
     $this->object = new GuzzleTransport($client);
 }
Пример #29
0
 /**
  * Creates a HTTP client.
  *
  * @param Response|Response[] $responses
  * @param array               $history
  *
  * @return HttpClient
  */
 private function createHttpClient($responses = array(), array &$history = array())
 {
     if (!is_array($responses)) {
         $responses = array($responses);
     }
     $stack = HandlerStack::create(new MockHandler($responses));
     $stack->push(Middleware::history($history));
     return new HttpClient(array('handler' => $stack));
 }
Пример #30
0
 public function __construct()
 {
     $history = Middleware::history($this->container);
     $this->mock = new MockHandler();
     $stack = HandlerStack::create($this->mock);
     // Add the history middleware to the handler stack.
     $stack->push($history);
     parent::__construct(['handler' => $stack]);
 }