当前位置: 首页>>代码示例>>PHP>>正文


PHP GuzzleHttp\Middleware类代码示例

本文整理汇总了PHP中GuzzleHttp\Middleware的典型用法代码示例。如果您正苦于以下问题:PHP Middleware类的具体用法?PHP Middleware怎么用?PHP Middleware使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。


在下文中一共展示了Middleware类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的PHP代码示例。

示例1: getHttpClient

 /**
  * 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;
 }
开发者ID:eldiddio,项目名称:php-ews,代码行数:30,代码来源:HttpPlayback.php

示例2: __construct

 /**
  * @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]);
 }
开发者ID:JoelESvensson,项目名称:bsd-api-php-guzzle6,代码行数:37,代码来源:Client.php

示例3: testSSO

 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));
 }
开发者ID:keboola,项目名称:gooddata-php-client,代码行数:29,代码来源:SSOTest.php

示例4: notifyWhenResponseIsComplete

 public function notifyWhenResponseIsComplete()
 {
     parent::$stack->push(Middleware::mapResponse(function (ResponseInterface $response) {
         print 'Response!' . PHP_EOL;
         return $response;
     }));
 }
开发者ID:rbadillap,项目名称:twitterstreaming,代码行数:7,代码来源:MyGuzzleMiddleware.php

示例5: post

 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;
 }
开发者ID:vantt,项目名称:vocabulary-crawler,代码行数:30,代码来源:GuzzleHttpRequest.php

示例6: __construct

 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]);
 }
开发者ID:tafint,项目名称:skype,代码行数:34,代码来源:Transport.php

示例7: buildClient

 /**
  * 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);
 }
开发者ID:lhas,项目名称:pep,代码行数:14,代码来源:Client.php

示例8: testValidateTicket

 /**
  * 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());
 }
开发者ID:pulibrary,项目名称:recap,代码行数:45,代码来源:CasValidatorTest.php

示例9: handle

 /**
  * 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]);
         }
     }
 }
开发者ID:phroggyy,项目名称:captainhook,代码行数:33,代码来源:TriggerWebhooksJob.php

示例10: testSend

 /**
  * @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()));
 }
开发者ID:maartenstaa,项目名称:gameanalytics-php,代码行数:32,代码来源:MessageTest.php

示例11: testSend

 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);
 }
开发者ID:netsensei,项目名称:europeana,代码行数:25,代码来源:ApiClientTest.php

示例12: initClient

 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]);
 }
开发者ID:keboola,项目名称:orchestrator-bundle,代码行数:7,代码来源:PingClient.php

示例13: testBasicClient

 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
         }
     }
 }
开发者ID:buuyers,项目名称:buuyers-api-php,代码行数:27,代码来源:BuuyersClientTest.php

示例14: register

 /**
  * 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));
         }
     });
 }
开发者ID:hannesvdvreken,项目名称:guzzle-debugbar,代码行数:36,代码来源:ServiceProvider.php

示例15: getClient

 /**
  * 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);
 }
开发者ID:opendi,项目名称:solrclient,代码行数:38,代码来源:AbstractCommand.php


注:本文中的GuzzleHttp\Middleware类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。