/** * @param string $method * @param string $uri * @param string|array $body */ public function sendRequest($method, $uri, $body = null) { if (false === $this->hasHost($uri)) { $uri = rtrim($this->host, '/') . '/' . ltrim($uri, '/'); } $this->request = $this->messageFactory->createRequest($method, $uri, $this->requestHeaders, $body); $this->response = $this->httpClient->sendRequest($this->request); if (null !== $this->responseStorage) { $this->responseStorage->writeRawContent((string) $this->response->getBody()); } }
/** * @return MessageFactory */ protected function getMessageFactory() { if ($this->messageFactory === null) { $this->messageFactory = MessageFactoryDiscovery::find(); } return $this->messageFactory; }
/** * This method is called immediately after the wrapper is initialized (f.e. by fopen() and file_get_contents()). * * @link http://www.php.net/manual/en/streamwrapper.stream-open.php * * @param string $path Specifies the URL that was passed to the original function. * @param string $mode The mode used to open the file, as detailed for fopen(). * @param int $options Holds additional flags set by the streams API. * @param string $opened_path If the path is opened successfully, and STREAM_USE_PATH is set. * * @return bool Returns TRUE on success or FALSE on failure. */ public static function stream_open($path, $mode, $options, &$opened_path) { // TODO Support POST requests or at least make sure they work $request = MessageFactoryDiscovery::find()->createRequest('GET', $path); self::$response = self::getHttpClient()->sendRequest($request); return true; }
/** * @return RequestFactory */ private function getRequestFactory() { if ($this->requestFactory === null) { $this->requestFactory = MessageFactoryDiscovery::find(); } return $this->requestFactory; }
/** * @param string $baseUrl * @param string[] $filePaths */ public function __construct($baseUrl, array $filePaths) { $this->baseUrl = $baseUrl; $this->client = HttpClientDiscovery::find(); $this->messageFactory = MessageFactoryDiscovery::find(); $this->fileLocator = new FileLocator($filePaths); }
/** * Constructor. * * @param string $key * @param string $secret * @param \Http\Client\HttpClient|null $http * @param \Http\Message\MessageFactory|null $factory */ public function __construct($key, $secret, HttpClient $http = null, MessageFactory $factory = null) { $this->key = $key; $this->secret = $secret; $this->http = $http ?: HttpClientDiscovery::find(); $this->factory = $factory ?: MessageFactoryDiscovery::find(); }
/** * Create new client instance * * If no specific transport, parser or serializer is passed, default implementations * are used. * * @param string $uri * @param TransportInterface $transport * @param Parser\ParserInterface $parser * @param Serializer\SerializerInterface $serializer */ public function __construct($uri = null, TransportInterface $transport = null, ParserInterface $parser = null, SerializerInterface $serializer = null) { $this->uri = $uri; $this->transport = $transport ?: new HttpAdapterTransport(MessageFactoryDiscovery::find(), HttpClientDiscovery::find()); $this->parser = $parser ?: new XmlReaderParser(); $this->serializer = $serializer ?: new XmlWriterSerializer(); }
/** * Uses php-http discovery to discover a message factory if one isn't set. * * @return Http\Message\MessageFactory */ public function messageFactory() { if (isset($this->messageFactory)) { return $this->messageFactory; } return MessageFactoryDiscovery::find(); }
/** * Constructor. * * @param ResponseFactory $responseFactory Response factory for creating response * @param array $config { * * @var string $remote_socket Remote entrypoint (can be a tcp or unix domain address) * @var int $timeout Timeout before canceling request * @var array $stream_context_options Context options as defined in the PHP documentation * @var array $stream_context_param Context params as defined in the PHP documentation * @var bool $ssl Use ssl, default to scheme from request, false if not present * @var int $write_buffer_size Buffer when writing the request body, defaults to 8192 * @var int $ssl_method Crypto method for ssl/tls, see PHP doc, defaults to STREAM_CRYPTO_METHOD_TLS_CLIENT * } */ public function __construct(ResponseFactory $responseFactory = null, array $config = []) { if (null === $responseFactory) { $responseFactory = MessageFactoryDiscovery::find(); } $this->responseFactory = $responseFactory; $this->config = $this->configure($config); }
/** * Set up bese env for test */ public function setUp() { $this->setMockClient(new MockClient()); $authentication = new BasicAuth(self::TESTRAIL_USER, self::TESTRAIL_TOKEN); $plugins[] = new AuthenticationPlugin($authentication); $pluginClient = new PluginClient($this->getMockClient(), $plugins); $this->setHttpMethodsClient($this->getMockBuilder(HttpMethodsClient::class)->enableProxyingToOriginalMethods()->setConstructorArgs([$pluginClient, MessageFactoryDiscovery::find()])->getMock()); }
/** * {@inheritdoc} */ public function sendRequest($method, $uri, array $headers = [], $body = null, $protocolVersion = '1.1') { $request = MessageFactoryDiscovery::find()->createRequest($method, $uri, $headers, $body, $protocolVersion); try { return $this->getHttpClient()->sendRequest($request); } catch (TransferException $e) { throw new LinkedInTransferException('Error while requesting data from LinkedIn.com: ' . $e->getMessage(), $e->getCode(), $e); } }
public function __construct(HttpClient $httpClient, MessageFactory $messageFactory = null, Serializer $serializer = null) { $this->httpClient = $httpClient; if ($serializer === null) { $serializer = new Serializer(NormalizerFactory::create(), [new JsonEncoder(new JsonEncode(), new JsonDecode()), new RawEncoder()]); } $this->serializer = $serializer; $this->messageFactory = $messageFactory ?: MessageFactoryDiscovery::find(); }
/** * @return HttpMethodsClient * * @throws EventClientFactoryCreateException */ protected static function createHttpClient() { try { $httpClient = new HttpMethodsClient(HttpClientDiscovery::find(), MessageFactoryDiscovery::find()); } catch (NotFoundException $exception) { throw new EventClientFactoryCreateException($exception->getMessage(), $exception->getCode(), $exception); } return $httpClient; }
/** * Initialize the React client. * * @param ResponseFactory|null $responseFactory * @param LoopInterface|null $loop * @param ReactClient|null $client * @param StreamFactory|null $streamFactory */ public function __construct(ResponseFactory $responseFactory = null, LoopInterface $loop = null, ReactClient $client = null, StreamFactory $streamFactory = null) { if (null !== $client && null === $loop) { throw new \RuntimeException('You must give a LoopInterface instance with the Client'); } $this->loop = $loop ?: ReactFactory::buildEventLoop(); $this->client = $client ?: ReactFactory::buildHttpClient($this->loop); $this->responseFactory = $responseFactory ?: MessageFactoryDiscovery::find(); $this->streamFactory = $streamFactory ?: StreamFactoryDiscovery::find(); }
/** * {@inheritdoc} */ public function sendRequest($method, $uri, array $body = [], $access_code, $protocolVersion = '1.1') { $request = MessageFactoryDiscovery::find()->createRequest($method, $this->getUrl() . $uri, ['authorization' => "Basic {$access_code}", 'content-type' => 'application/json', 'accept' => 'application/json'], json_encode($body), $protocolVersion); try { $response = ResponseHandler::convert($this->getHttpClient()->sendRequest($request), 'psr7'); ResponseHandler::handleWithErrors($response); return $response; } catch (TransferException $e) { throw new ZenviaRequestException('Error while requesting data from Zenvia API: ' . $e->getMessage(), $e->getCode(), $e); } }
/** * AbstractHttpProvider Constructor. * * @param HttpClient $client HttpClient makes HTTP requests. * @param MessageFactory $messageFactory MessageFactory creates Request objects. */ public function __construct(HttpClient $client = null, MessageFactory $messageFactory = null) { if (null === $client && !class_exists('Http\\Discovery\\HttpClientDiscovery')) { throw ServiceMissingException::noHttpClient(); } $this->client = $client ?: \Http\Discovery\HttpClientDiscovery::find(); if (null === $messageFactory && !class_exists('Http\\Discovery\\MessageFactoryDiscovery')) { throw ServiceMissingException::noMessageFactory(); } $this->messageFactory = $messageFactory ?: \Http\Discovery\MessageFactoryDiscovery::find(); }
/** * @param string $url * @param string $token * * @return HttpClient */ public static function create($url, $token) { $plugins = [new Plugin\RedirectPlugin(), new Plugin\RetryPlugin(['retries' => 5]), new Plugin\DecoderPlugin(), new Plugin\ErrorPlugin()]; if ($token) { $plugins[] = new Plugin\AuthenticationPlugin(new QueryParam(['api_key' => $token])); } $client = new PluginClient(Discovery\HttpClientDiscovery::find(), $plugins); $streamFactory = Discovery\StreamFactoryDiscovery::find(); $builder = new MultipartStreamBuilder($streamFactory); return new HttpPlugHttpAdapterClient($client, $url, Discovery\MessageFactoryDiscovery::find(), $builder); }
/** * Constructor. * * @param ResponseFactory $responseFactory Response factory for creating response * @param array $config { * * @var string $remote_socket Remote entrypoint (can be a tcp or unix domain address) * @var int $timeout Timeout before canceling request * @var array $stream_context_options Context options as defined in the PHP documentation * @var array $stream_context_param Context params as defined in the PHP documentation * @var bool $ssl Use ssl, default to scheme from request, false if not present * @var int $write_buffer_size Buffer when writing the request body, defaults to 8192 * @var int $ssl_method Crypto method for ssl/tls, see PHP doc, defaults to STREAM_CRYPTO_METHOD_TLS_CLIENT * } * * @throws \LogicException When MessageFactory is not provided and cannot be discovered */ public function __construct(ResponseFactory $responseFactory = null, array $config = []) { if (null === $responseFactory && !class_exists('\\Http\\Discovery\\MessageFactoryDiscovery')) { throw new \LogicException('No response factory provided and no discovery service is present to guess it, maybe you need to install php-http/discovery package?'); } if (null === $responseFactory) { $responseFactory = MessageFactoryDiscovery::find(); } $this->responseFactory = $responseFactory; $this->config = $this->configure($config); }
/** * {@inheritdoc} */ public function sendRequest(RequestInterface $request, array $options = []) { $this->requests[] = $request; if ($this->exception) { throw $this->exception; } if (count($this->responses) > 0) { return array_shift($this->responses); } return MessageFactoryDiscovery::find()->createResponse(); }
/** * set up basic mocks. */ public function setUp() { parent::setUp(); $this->representProcessor = new RepresentProcessor(); $this->eventRepresentation = new EventRepresentation(); $this->representProcessor->addRepresentation($this->eventRepresentation); $this->mockClient = new MockClient(); $this->pluginClient = new PluginClient($this->mockClient); $this->httpMethodsClient = $this->getMockBuilder(HttpMethodsClient::class)->setConstructorArgs([$this->pluginClient, MessageFactoryDiscovery::find()])->enableProxyingToOriginalMethods()->getMock(); $this->validationResponse = ValidationResponseFactory::createValidation('Event'); $this->eventClient = new EventClient('https://events.pagerduty.com/generic/2010-04-15', $this->httpMethodsClient, $this->representProcessor, $this->validationResponse); }
/** * @param HttpAdapter|null $adapter * @param MessageFactory|null $messageFactory */ public function __construct(HttpAdapter $adapter = null, MessageFactory $messageFactory = null) { // guess http adapter $this->adapter = $adapter; if (!isset($messageFactory)) { $messageFactory = MessageFactoryDiscovery::find(); } if (!$messageFactory instanceof InternalMessageFactory) { $messageFactory = new Message\InternalMessageFactory($messageFactory); } $this->messageFactory = $messageFactory; }
/** * Constructor. * * Supported options: * * - base_uri Default application hostname, optionally including base URL, * for purge and refresh requests (optional). This is required if you * purge and refresh paths instead of absolute URLs. * * @param array $servers Caching proxy server hostnames or IP * addresses, including port if not port 80. * E.g. ['127.0.0.1:6081'] * @param array $options List of options for the client * @param HttpAsyncClient|null $httpClient Client capable of sending HTTP requests. If no * client is supplied, a default one is created * @param MessageFactory|null $messageFactory Factory for PSR-7 messages. If none supplied, * a default one is created * @param UriFactory|null $uriFactory Factory for PSR-7 URIs. If not specified, a * default one is created */ public function __construct(array $servers, array $options = [], HttpAsyncClient $httpClient = null, MessageFactory $messageFactory = null, UriFactory $uriFactory = null) { if (!$httpClient) { $httpClient = HttpAsyncClientDiscovery::find(); } if (!$uriFactory) { $uriFactory = UriFactoryDiscovery::find(); } $this->options = $this->getDefaultOptions()->resolve($options); $this->httpAdapter = new HttpAdapter($servers, $this->options['base_uri'], $httpClient, $uriFactory); $this->messageFactory = $messageFactory ?: MessageFactoryDiscovery::find(); }
/** * {@inheritdoc} */ public function sendRequest(RequestInterface $request) { $this->requests[] = $request; if (count($this->exceptions) > 0) { throw array_shift($this->exceptions); } if (count($this->responses) > 0) { return array_shift($this->responses); } // Return success response by default return MessageFactoryDiscovery::find()->createResponse(); }
/** * @param ClientInterface|Browser|null $client * @param ResponseFactory|null $responseFactory */ public function __construct($client = null, ResponseFactory $responseFactory = null) { $this->client = $client; if ($this->client === null) { $this->client = new FileGetContents(); $this->client->setMaxRedirects(0); } if (!$this->client instanceof ClientInterface && !$this->client instanceof Browser) { throw new \InvalidArgumentException(sprintf('The client passed to the Buzz adapter must either implement %s or be an instance of %s. You passed %s.', ClientInterface::class, Browser::class, is_object($client) ? get_class($client) : gettype($client))); } $this->responseFactory = $responseFactory ?: MessageFactoryDiscovery::find(); }
/** * Create a response object. * * @param string $raw The raw response string * * @return \Psr\Http\Message\ResponseInterface */ private function createResponse($raw) { if (version_compare(curl_version()['version'], '7.30.0', '<')) { $pos = strlen($raw) - curl_getinfo($this->curl, CURLINFO_SIZE_DOWNLOAD); } else { $pos = curl_getinfo($this->curl, CURLINFO_HEADER_SIZE); } list($statusLine, $headers) = $this->parseHeaders(rtrim(substr($raw, 0, $pos))); $body = strlen($raw) > $pos ? substr($raw, $pos) : ''; if (!preg_match('|^HTTP/([12].[01]) ([1-9][0-9][0-9]) (.*?)$|', $statusLine, $matches)) { throw new HttpException('Not a HTTP response'); } return MessageFactoryDiscovery::find()->createResponse((int) $matches[2], $matches[3], $headers, $body, $matches[1]); }
/** * Register the http related stuff. * * @param Application $app */ private function registerHttp(Application $app) { $app->singleton('swap.http_client', function ($app) { if ($httpClient = $app->config->get('swap.http_client')) { return $app[$httpClient]; } return HttpClientDiscovery::find(); }); $app->singleton('swap.request_factory', function ($app) { if ($requestFactory = $app->config->get('swap.request_factory')) { return $app[$requestFactory]; } return MessageFactoryDiscovery::find(); }); }
/** * @param string $method * @param string $url * @param array $data * * @return array * * @throws HttpException */ public function send($method, $url, $body = null, $headers = array()) { $request = MessageFactoryDiscovery::find()->createRequest($method, $url, $headers, $body); try { $response = $this->getClient()->sendRequest($request); } catch (TransferException $e) { $message = 'Error sending request. '; if ($e instanceof \Http\Client\Exception\HttpException) { $message .= (string) $e->getResponse()->getBody(); } throw new HttpException($message, $e->getCode(), $e); } // TODO add more error checks return json_decode($response->getBody()->__toString(), true); }
/** * Register php-http interfaces to container. */ protected function registerHttplugFactories() { $this->app->bind('httplug.message_factory.default', function ($app) { return MessageFactoryDiscovery::find(); }); $this->app->alias('httplug.message_factory.default', MessageFactory::class); $this->app->alias('httplug.message_factory.default', ResponseFactory::class); $this->app->bind('httplug.uri_factory.default', function ($app) { return UriFactoryDiscovery::find(); }); $this->app->alias('httplug.uri_factory.default', UriFactory::class); $this->app->bind('httplug.stream_factory.default', function ($app) { return StreamFactoryDiscovery::find(); }); $this->app->alias('httplug.stream_factory.default', StreamFactory::class); }
/** * Create a request. * * @param string $method * @param string $uri * @param array $headers * * @return RequestInterface * * @throws \Exception */ private function createRequest($method, $uri, $headers) { $uri = $this->createUri($uri); if ($uri->getHost() === '') { // Add base URI host $uri = $uri->withHost($this->hostname); } if (!$uri->getPort()) { $uri = $uri->withPort($this->port); } if ($uri->getScheme() === '') { $uri = $uri->withScheme('http'); } return MessageFactoryDiscovery::find()->createRequest($method, $uri, $headers); }
/** * @param ClientInterface|null $client * @param MessageFactory|null $messageFactory */ public function __construct(ClientInterface $client = null, MessageFactory $messageFactory = null) { $this->client = $client ?: new Client(); $this->messageFactory = $messageFactory ?: MessageFactoryDiscovery::find(); }