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]);
 }
 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]);
 }
Exemple #3
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 #4
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");
     }
 }
 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 performTestRequest($logger, $request, $response)
 {
     $stack = new HandlerStack(new MockHandler([$response]));
     $stack->push(LoggingMiddleware::forLogger($logger));
     $handler = $stack->resolve();
     return $handler($request, [])->wait();
 }
Exemple #7
0
 private function configureResponseHandler(HandlerStack $handlerStack)
 {
     $handlerStack->remove('wechatClient:response');
     $handlerStack->push(function (callable $handler) {
         return function (RequestInterface $request, array $options = []) use($handler) {
             return $handler($request, $options)->then(function (ResponseInterface $response) use($request) {
                 // Non-success page, so we won't attempt to parse.
                 if ($response->getStatusCode() >= 300) {
                     return $response;
                 }
                 // Check if the response should be JSON decoded
                 $parse = ['application/json', 'text/json', 'text/plain'];
                 if (preg_match('#' . implode('|', $parse) . '#', $response->getHeaderLine('Content-Type')) < 1) {
                     return $response;
                 }
                 // Begin parsing JSON body.
                 $body = (string) $response->getBody();
                 $json = json_decode($body);
                 if (json_last_error() !== JSON_ERROR_NONE) {
                     throw new BadResponseFormatException(json_last_error_msg(), json_last_error());
                 }
                 if (isset($json->errcode) && $json->errcode != 0) {
                     $message = isset($json->errmsg) ? $json->errmsg : '';
                     $code = $json->errcode;
                     throw new APIErrorException($message, $code, $request, $response);
                 }
                 return $response;
             });
         };
     }, 'wechatClient:response');
 }
 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);
 }
Exemple #9
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);
 }
 /**
  * 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);
     }
 }
 /**
  * @inheritdoc
  * @SuppressWarnings(PHPMD.StaticAccess)
  */
 public function attachMiddleware(HandlerStack $stack)
 {
     $stack->push(Middleware::mapRequest(function (RequestInterface $request) {
         $this->onRequestBeforeSend($request);
         return $request;
     }));
     $stack->push(function (callable $handler) {
         return function (RequestInterface $request, array $options) use($handler) {
             $promise = $handler($request, $options);
             return $promise->then(function (ResponseInterface $response) use($request) {
                 $this->onRequestComplete($request, $response);
                 return $response;
             });
         };
     });
     return $stack;
 }
 /**
  * @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);
 }
 /**
  * @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]);
 }
 /**
  * @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;
 }
Exemple #15
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]);
 }
 /**
  * Push function to middleware handler
  *
  * @param HandlerStack $stack
  *
  * @return HandlerStack
  */
 public function push(HandlerStack $stack)
 {
     $stack->push(Middleware::mapRequest(function (RequestInterface $request) {
         $this->initEvent($request);
         return $request;
     }), 'eventDispatcher_initEvent');
     $stack->push(function (callable $handler) {
         return function (RequestInterface $request, array $options) use($handler) {
             $promise = $handler($request, $options);
             return $promise->then(function (ResponseInterface $response) use($request) {
                 $this->sendEvent($request, $response);
                 return $response;
             }, function (\Exception $reason) use($request) {
                 $this->sendErrorEvent($request, $reason);
                 throw $reason;
             });
         };
     }, 'eventDispatcher_dispatch');
     return $stack;
 }
Exemple #17
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 #18
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 #21
0
 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);
     });
 }
 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);
 }
Exemple #24
0
 /**
  * @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;
 }
 public function register(Application $app)
 {
     /** @var \Qandidate\Toggle\ToggleManager $toggles */
     $toggles = $app['toggles'];
     $importFromSapi = $toggles->active('import-from-sapi', $app['toggles.context']);
     $app['udb2_log_handler'] = $app->share(function (Application $app) {
         return new \Monolog\Handler\StreamHandler(__DIR__ . '/../log/udb2.log');
     });
     $app['udb2_deserializer_locator'] = $app->share(function (Application $app) {
         $deserializerLocator = new SimpleDeserializerLocator();
         $deserializerLocator->registerDeserializer(new StringLiteral('application/vnd.cultuurnet.udb2-events.actor-created+json'), new ActorCreatedJSONDeserializer());
         $deserializerLocator->registerDeserializer(new StringLiteral('application/vnd.cultuurnet.udb2-events.actor-updated+json'), new ActorUpdatedJSONDeserializer());
         $deserializerLocator->registerDeserializer(new StringLiteral('application/vnd.cultuurnet.udb2-events.event-created+json'), new EventCreatedJSONDeserializer());
         $deserializerLocator->registerDeserializer(new StringLiteral('application/vnd.cultuurnet.udb2-events.event-updated+json'), new EventUpdatedJSONDeserializer());
         return $deserializerLocator;
     });
     $app['udb2_event_bus_forwarding_consumer_factory'] = $app->share(function (Application $app) {
         return new EventBusForwardingConsumerFactory($app['amqp-execution-delay'], $app['amqp.connection'], $app['logger.amqp.event_bus_forwarder'], $app['udb2_deserializer_locator'], $app['event_bus'], new StringLiteral($app['config']['amqp']['consumer_tag']));
     });
     $app['amqp.udb2_event_bus_forwarding_consumer'] = $app->share(function (Application $app) {
         $consumerConfig = $app['config']['amqp']['consumers']['udb2'];
         $exchange = new StringLiteral($consumerConfig['exchange']);
         $queue = new StringLiteral($consumerConfig['queue']);
         /** @var EventBusForwardingConsumerFactory $consumerFactory */
         $consumerFactory = $app['udb2_event_bus_forwarding_consumer_factory'];
         return $consumerFactory->create($exchange, $queue);
     });
     $app['cdbxml_enricher_http_client_adapter'] = $app->share(function (Application $app) {
         $handlerStack = new HandlerStack(\GuzzleHttp\choose_handler());
         $handlerStack->push(Middleware::prepareBody(), 'prepare_body');
         $responseTimeout = 3;
         $connectTimeout = 1;
         if (isset($app['udb2_cdbxml_enricher.http_response_timeout'])) {
             $responseTimeout = $app['udb2_cdbxml_enricher.http_response_timeout'];
         }
         if (isset($app['udb2_cdbxml_enricher.http_connect_timeout'])) {
             $connectTimeout = $app['udb2_cdbxml_enricher.http_connect_timeout'];
         }
         $client = new Client(['handler' => $handlerStack, 'timeout' => $responseTimeout, 'connect_timeout' => $connectTimeout]);
         return new ClientAdapter($client);
     });
     $app['cdbxml_enricher_logger'] = $app->share(function (Application $app) {
         $logger = new \Monolog\Logger('udb2-events-cdbxml-enricher');
         $logger->pushHandler($app['udb2_log_handler']);
         return $logger;
     });
     $app['udb2_events_cdbxml_enricher'] = $app->share(function (Application $app) use($importFromSapi) {
         $enricher = new EventCdbXmlEnricher($app['event_bus'], $app['cdbxml_enricher_http_client_adapter']);
         $enricher->setLogger($app['cdbxml_enricher_logger']);
         if ($importFromSapi) {
             $eventUrlFormat = $app['config']['udb2_import']['event_url_format'];
             if (!isset($eventUrlFormat)) {
                 throw new \Exception('can not import events from sapi without configuring an url format');
             }
             $transformer = new OfferToSapiUrlTransformer($eventUrlFormat);
             $enricher->withUrlTransformer($transformer);
         }
         return $enricher;
     });
     $app['udb2_actor_events_cdbxml_enricher'] = $app->share(function (Application $app) use($importFromSapi) {
         $enricher = new ActorEventCdbXmlEnricher($app['event_bus'], $app['cdbxml_enricher_http_client_adapter']);
         $enricher->setLogger($app['cdbxml_enricher_logger']);
         if ($importFromSapi) {
             $actorUrlFormat = $app['config']['udb2_import']['actor_url_format'];
             if (!isset($actorUrlFormat)) {
                 throw new \Exception('can not import actors from sapi without configuring an url format');
             }
             $transformer = new OfferToSapiUrlTransformer($actorUrlFormat);
             $enricher->withUrlTransformer($transformer);
         }
         return $enricher;
     });
     $app['udb2_events_to_udb3_place_applier'] = $app->share(function (Application $app) {
         $applier = new EventApplier(new LabeledAsUDB3Place(), $app['place_repository'], new EventToUDB3PlaceFactory());
         $logger = new \Monolog\Logger('udb2-events-to-udb3-place-applier');
         $logger->pushHandler($app['udb2_log_handler']);
         $applier->setLogger($logger);
         return $applier;
     });
     $app['udb2_events_to_udb3_event_applier'] = $app->share(function (Application $app) {
         $applier = new EventApplier(new Not(new LabeledAsUDB3Place()), $app['event_repository'], new EventToUDB3EventFactory());
         $logger = new \Monolog\Logger('udb2-events-to-udb3-event-applier');
         $logger->pushHandler($app['udb2_log_handler']);
         $applier->setLogger($logger);
         return $applier;
     });
     $app['udb2_actor_events_to_udb3_place_applier'] = $app->share(function (Application $app) {
         $applier = new ActorEventApplier($app['place_repository'], new ActorToUDB3PlaceFactory(), new QualifiesAsPlaceSpecification());
         $logger = new \Monolog\Logger('udb2-actor-events-to-udb3-place-applier');
         $logger->pushHandler($app['udb2_log_handler']);
         $applier->setLogger($logger);
         return $applier;
     });
     $app['udb2_actor_events_to_udb3_organizer_applier'] = $app->share(function (Application $app) {
         $applier = new ActorEventApplier($app['organizer_repository'], new ActorToUDB3OrganizerFactory(), new QualifiesAsOrganizerSpecification());
         $logger = new \Monolog\Logger('udb2-actor-events-to-udb3-organizer-applier');
         $logger->pushHandler($app['udb2_log_handler']);
         $applier->setLogger($logger);
         return $applier;
     });
     $app['udb2_label_importer'] = $app->share(function (Application $app) {
         $labelImporter = new LabelImporter($app['labels.constraint_aware_service']);
         $logger = new \Monolog\Logger('udb2-label-importer');
         $logger->pushHandler($app['udb2_log_handler']);
         $labelImporter->setLogger($logger);
         return $labelImporter;
     });
     $app['udb2_event_cdbid_extractor'] = $app->share(function (Application $app) {
         return new EventCdbIdExtractor($app['udb2_place_external_id_mapping_service'], $app['udb2_organizer_external_id_mapping_service']);
     });
     $app['udb2_place_external_id_mapping_service'] = $app->share(function (Application $app) {
         $yamlFileLocation = $app['udb2_place_external_id_mapping.yml_file_location'];
         return $app['udb2_external_id_mapping_service_factory']($yamlFileLocation);
     });
     $app['udb2_organizer_external_id_mapping_service'] = $app->share(function (Application $app) {
         $yamlFileLocation = $app['udb2_organizer_external_id_mapping.yml_file_location'];
         return $app['udb2_external_id_mapping_service_factory']($yamlFileLocation);
     });
     $app['udb2_external_id_mapping_service_factory'] = $app->protect(function ($yamlFileLocation) {
         $map = [];
         if (file_exists($yamlFileLocation)) {
             $yaml = file_get_contents($yamlFileLocation);
             $yaml = Yaml::parse($yaml);
             if (is_array($yaml)) {
                 $map = $yaml;
             }
         }
         return new ArrayMappingService($map);
     });
 }
Exemple #26
0
 /**
  * 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;
 }
Exemple #27
0
 /**
  * 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;
 }
 public function testLogsRequestsAndErrors()
 {
     $h = new MockHandler([new Response(404)]);
     $stack = new HandlerStack($h);
     $logger = new Logger();
     $formatter = new MessageFormatter('{code} {error}');
     $stack->push(Middleware::log($logger, $formatter));
     $stack->push(Middleware::httpErrors());
     $comp = $stack->resolve();
     $p = $comp(new Request('PUT', 'http://www.google.com'), ['http_errors' => true]);
     $p->wait(false);
     $this->assertContains('PUT http://www.google.com', $logger->output);
     $this->assertContains('404 Not Found', $logger->output);
 }
Exemple #29
0
 public function registerHandlers(HandlerStack $stack)
 {
     $stack->push(BlackfireMiddleware::create($this->blackfire), 'blackfire');
 }
 public function testIgnoresIfExpectIsPresent()
 {
     $bd = Psr7\stream_for(fopen(__DIR__ . '/../composer.json', 'r'));
     $h = new MockHandler([function (RequestInterface $request) {
         $this->assertEquals(['Foo'], $request->getHeader('Expect'));
         return new Response(200);
     }]);
     $m = Middleware::prepareBody();
     $stack = new HandlerStack($h);
     $stack->push($m);
     $comp = $stack->resolve();
     $p = $comp(new Request('PUT', 'http://www.google.com', ['Expect' => 'Foo'], $bd), ['expect' => true]);
     $this->assertInstanceOf(PromiseInterface::class, $p);
     $response = $p->wait();
     $this->assertEquals(200, $response->getStatusCode());
 }