Пример #1
1
 /**
  * @param array $fields
  *
  * @return string
  */
 public function notifyValidate(array $fields)
 {
     $fields['cmd'] = self::CMD_NOTIFY_VALIDATE;
     $headers = array('Content-Type' => 'application/x-www-form-urlencoded');
     $request = $this->messageFactory->createRequest('POST', $this->getIpnEndpoint(), $headers, http_build_query($fields));
     $response = $this->client->send($request);
     if (false == ($response->getStatusCode() >= 200 && $response->getStatusCode() < 300)) {
         throw HttpException::factory($request, $response);
     }
     $result = $response->getBody()->getContents();
     return self::NOTIFY_VERIFIED === $result ? self::NOTIFY_VERIFIED : self::NOTIFY_INVALID;
 }
Пример #2
1
 /**
  * @param array $fields
  *
  * @throws HttpException
  *
  * @return array
  */
 protected function doRequest(array $fields)
 {
     $headers = array('Content-Type' => 'application/x-www-form-urlencoded');
     $request = $this->messageFactory->createRequest('POST', $this->getApiEndpoint(), $headers, http_build_query($fields));
     $response = $this->client->send($request);
     if (false == ($response->getStatusCode() >= 200 && $response->getStatusCode() < 300)) {
         throw HttpException::factory($request, $response);
     }
     $result = [];
     parse_str($response->getBody()->getContents(), $result);
     foreach ($result as &$value) {
         $value = urldecode($value);
     }
     return $result;
 }
 /**
  * Read a response from a socket
  *
  * @param RequestInterface $request
  * @param resource         $socket
  *
  * @throws NetworkException When the response cannot be read
  *
  * @return ResponseInterface
  */
 protected function readResponse(RequestInterface $request, $socket)
 {
     $headers = [];
     $reason = null;
     $status = null;
     $protocol = null;
     while (($line = fgets($socket)) !== false) {
         if (rtrim($line) === '') {
             break;
         }
         $headers[] = trim($line);
     }
     $parts = explode(' ', array_shift($headers), 3);
     if (count($parts) <= 1) {
         throw new NetworkException('Cannot read the response', $request);
     }
     $protocol = substr($parts[0], -3);
     $status = $parts[1];
     if (isset($parts[2])) {
         $reason = $parts[2];
     }
     // Set the size on the stream if it was returned in the response
     $responseHeaders = [];
     foreach ($headers as $header) {
         $headerParts = explode(':', $header, 2);
         $responseHeaders[trim($headerParts[0])] = isset($headerParts[1]) ? trim($headerParts[1]) : '';
     }
     $response = $this->messageFactory->createResponse($status, $reason, $protocol, $responseHeaders, null);
     $stream = $this->createStream($socket, $response);
     return $response->withBody($stream);
 }
Пример #4
0
 /**
  * {@inheritdoc}
  */
 public function send($method, $uri, array $headers = [], $data = [], array $files = [], array $options = [])
 {
     if ($data instanceof StreamInterface && !empty($files)) {
         throw new \InvalidArgumentException('A data instance of Psr\\Http\\Message\\StreamInterface and $files parameters should not be passed together.');
     }
     $request = $this->messageFactory->createInternalRequest($method, $uri, isset($options['protocolVersion']) ? $options['protocolVersion'] : '1.1', $headers, $data, $files);
     return $this->sendRequest($request);
 }
Пример #5
0
 public function createSnitcherRequest(UriInterface $uri, Message $message)
 {
     $headers = $this->createHeaders($this->userAgent);
     $body = $this->createBody($message);
     $stream = $this->streamFactory->createStream($body);
     $request = $this->messageFactory->createRequest("POST", $uri, $headers, $stream);
     return $request;
 }
Пример #6
0
 /**
  * Call an API endpoint.
  *
  * @param string $someArgument
  *
  * @return string
  */
 public function someOperation($someArgument)
 {
     $request = $this->messageFactory->createRequest('GET', self::ENDPOINT . '/some_operation?argument=' . $someArgument);
     try {
         $response = $this->httpClient->sendRequest($request);
     } catch (\Http\Client\Exception $e) {
         throw new \RuntimeException('Something happened during HTTP request');
     }
     return (string) $response->getBody();
 }
Пример #7
0
 /**
  * @param array $fields
  *
  * @return array
  */
 protected function doRequest($method, array $fields)
 {
     $headers = [];
     $request = $this->messageFactory->createRequest($method, $this->getApiEndpoint(), $headers, http_build_query($fields));
     $response = $this->client->send($request);
     if (false == ($response->getStatusCode() >= 200 && $response->getStatusCode() < 300)) {
         throw HttpException::factory($request, $response);
     }
     return $response;
 }
Пример #8
0
 /**
  * @param callable $callback
  */
 public function listenEvents(callable $callback)
 {
     $request = $this->messageFactory->createRequest('GET', '/events');
     $response = $this->httpClient->sendRequest($request);
     $stream = $response->getBody();
     while (!$stream->eof()) {
         $line = \GuzzleHttp\Psr7\readline($stream);
         if (null !== ($raw = json_decode($line, true))) {
             call_user_func($callback, new Event($raw));
         }
     }
 }
Пример #9
0
 /**
  * Create an PSR-7 Request from the API Schema
  *
  * @param RequestDefinition $definition
  * @param array $params An array of parameters
  *
  * @todo handle default values for request parameters
  *
  * @return RequestInterface
  */
 private function createRequestFromDefinition(RequestDefinition $definition, array $params)
 {
     $contentType = $definition->getContentTypes()[0];
     $requestParameters = $definition->getRequestParameters();
     $path = [];
     $query = [];
     $headers = ['Content-Type' => $contentType];
     $body = null;
     foreach ($params as $name => $value) {
         $requestParameter = $requestParameters->getByName($name);
         if ($requestParameter === null) {
             throw new \InvalidArgumentException($name . ' is not a defined request parameter');
         }
         switch ($requestParameter->getLocation()) {
             case 'path':
                 $path[$name] = $value;
                 break;
             case 'query':
                 $query[$name] = $value;
                 break;
             case 'header':
                 $query[$name] = $value;
                 break;
             case 'body':
                 $body = $this->serializeRequestBody($value, $contentType);
         }
     }
     $request = $this->messageFactory->createRequest($definition->getMethod(), $this->buildRequestUri($definition->getPathTemplate(), $path, $query), $headers, $body);
     return $request;
 }
 /**
  * @feature Ssl connection
  */
 public function testSsl()
 {
     $request = self::$messageFactory->createRequest('GET', 'https://httpbin.org/get');
     $response = $this->createClient()->sendRequest($request);
     $this->assertInstanceOf('Psr\\Http\\Message\\ResponseInterface', $response);
     $this->assertSame(200, $response->getStatusCode());
 }
Пример #11
0
 /**
  * Create new ResponseBuilder instance
  *
  * @return ResponseBuilder
  *
  * @throws \RuntimeException If creating the stream from $body fails.
  */
 private function createResponseBuilder()
 {
     try {
         $body = $this->streamFactory->createStream(fopen('php://temp', 'w+'));
     } catch (\InvalidArgumentException $e) {
         throw new \RuntimeException('Can not create "php://temp" stream.');
     }
     $response = $this->messageFactory->createResponse(200, null, [], $body);
     return new ResponseBuilder($response);
 }
Пример #12
0
 /**
  * @param string $method
  * @param string $uri
  * @param array  $headers
  * @param array  $body
  *
  * @return \Psr\Http\Message\ResponseInterface
  */
 private function sendMultipartRequest(string $method, string $uri, array $headers, array $body)
 {
     $builder = new MultipartStreamBuilder($this->streamFactory);
     foreach ($body as $item) {
         $builder->addResource($item['name'], $item['contents']);
     }
     $multipartStream = $builder->build();
     $boundary = $builder->getBoundary();
     $request = $this->messageFactory->createRequest($method, $uri, array_merge(['Content-Type' => 'multipart/form-data; boundary=' . $boundary], $headers), $multipartStream);
     return $this->getHttpClient()->sendRequest($request);
 }
 /**
  * @param array  $params
  * @param array  $files
  * @param string $method
  * @param string $url
  *
  * @return RequestInterface
  */
 private function createRequest(array $params, array $files, $method, $url)
 {
     if (!count($params) && !count($files)) {
         return $this->factory->createRequest($method, $url);
     }
     $builder = clone $this->multipartStreamBuilder;
     foreach ($params as $k => $v) {
         $builder->addResource($k, $v);
     }
     foreach ($files as $k => $file) {
         $builder->addResource($k, fopen($file, 'r'), ['filename' => $file]);
     }
     return $this->factory->createRequest($method, $url, ['Content-Type' => 'multipart/form-data; boundary=' . $builder->getBoundary()], $builder->build());
 }
Пример #14
0
 /**
  * @param array $fields
  *
  * @return array
  */
 protected function doRequest(array $fields)
 {
     $headers = array('Content-Type' => 'application/x-www-form-urlencoded');
     $request = $this->messageFactory->createRequest('POST', $this->getApiEndpoint(), $headers, http_build_query($fields));
     $response = $this->client->send($request);
     if (false == ($response->getStatusCode() >= 200 && $response->getStatusCode() < 300)) {
         throw HttpException::factory($request, $response);
     }
     $result = json_decode($response->getBody()->getContents());
     if (null === $result) {
         throw new LogicException("Response content is not valid json: \n\n{$response->getBody()->getContents()}");
     }
     return $result;
 }
Пример #15
0
 /**
  * {@inheritdoc}
  */
 public function request($url, array $options = [], $method = 'GET', $json = true)
 {
     try {
         $options = array_replace(['body' => null, 'headers' => [], 'query' => []], $options);
         // Prepend the SharePoint Site URL when only the path is passed
         if (filter_var($url, FILTER_VALIDATE_URL) === false) {
             $url = $this->getUrl($url);
         }
         if (!empty($options['query'])) {
             $url = sprintf('%s?%s', $url, http_build_query($options['query']));
         }
         $request = $this->message->createRequest($method, $url, $options['headers'], $options['body']);
         $response = $this->client->sendRequest($request);
         return $json ? $this->parseResponse($response) : $response;
     } catch (HttpClientException $e) {
         throw new SPRuntimeException('Unable to make HTTP request', 0, $e);
     }
 }
Пример #16
0
 /**
  * Sends a PSR-7 request.
  *
  * @param RequestInterface $request
  *
  * @return ResponseInterface
  *
  * @throws \Http\Client\Exception If an error happens during processing the request.
  * @throws \Exception             If processing the request is impossible (eg. bad configuration).
  */
 public function sendRequest(RequestInterface $request)
 {
     $body = (string) $request->getBody();
     $headers = [];
     foreach (array_keys($request->getHeaders()) as $headerName) {
         if (strtolower($headerName) === 'content-length') {
             $values = array(strlen($body));
         } else {
             $values = $request->getHeader($headerName);
         }
         foreach ($values as $value) {
             $headers[] = $headerName . ': ' . $value;
         }
     }
     $streamContextOptions = array('protocol_version' => $request->getProtocolVersion(), 'method' => $request->getMethod(), 'header' => implode("\r\n", $headers), 'timeout' => $this->timeout, 'ignore_errors' => true, 'follow_location' => $this->followRedirects ? 1 : 0, 'max_redirects' => 100);
     if (strlen($body) > 0) {
         $streamContextOptions['content'] = $body;
     }
     $context = stream_context_create(array('http' => $streamContextOptions, 'https' => $streamContextOptions));
     $httpHeadersOffset = 0;
     $finalUrl = (string) $request->getUri();
     stream_context_set_params($context, array('notification' => function ($code, $severity, $msg, $msgCode, $bytesTx, $bytesMax) use(&$remoteDocument, &$http_response_header, &$httpHeadersOffset) {
         if ($code === STREAM_NOTIFY_REDIRECTED) {
             $finalUrl = $msg;
             $httpHeadersOffset = count($http_response_header);
         }
     }));
     $response = $this->messageFactory->createResponse();
     if (false === ($responseBody = @file_get_contents((string) $request->getUri(), false, $context))) {
         if (!isset($http_response_header)) {
             throw new NetworkException('Unable to execute request', $request);
         }
     } else {
         $response = $response->withBody($this->streamFactory->createStream($responseBody));
     }
     $parser = new HeaderParser();
     try {
         return $parser->parseArray(array_slice($http_response_header, $httpHeadersOffset), $response);
     } catch (\Exception $e) {
         throw new RequestException($e->getMessage(), $request, $e);
     }
 }
Пример #17
0
 /**
  * Unserialize data from binary string.
  *
  * @param string $string
  *
  * @return MessageInterface Unserialized data.
  *
  * @throws UnserializeException If $string can not be unserialized.
  *
  * @since 1.0
  */
 public function unserialize($string)
 {
     $parts = explode("\r\n", $string, 2);
     if (count($parts) !== 2) {
         throw new UnserializeException('Serialized data does not contain message type ID');
     }
     $type = $parts[0];
     $string = $parts[1];
     switch ($type) {
         case self::REQUEST:
             list($part, $string) = explode("\r\n", $string, 2);
             $pattern = "/^HTTP\\/(?P<version>\\d\\.\\d) (?P<method>[A-Z]+) (?P<uri>.+)\$/";
             if (preg_match($pattern, $part, $matches) === 0) {
                 throw new UnserializeException(sprintf('Line "%s" not matches HTTP heading format', $part));
             }
             $message = $this->messageFactory->createRequest($matches['method'], $matches['uri']);
             $message = $message->withProtocolVersion($matches['version']);
             break;
         case self::RESPONSE:
             $message = $this->messageFactory->createResponse();
             break;
         default:
             throw new UnserializeException();
     }
     /** @var MessageInterface $message */
     list($part, $string) = explode("\r\n\r\n", $string, 2);
     $headers = explode("\r\n", $part);
     foreach ($headers as $header) {
         list($name, $value) = explode(':', $header, 2);
         $name = trim(urldecode($name));
         $value = trim(urldecode($value));
         if ($message->hasHeader($name)) {
             $message = $message->withAddedHeader($name, $value);
         } else {
             $message = $message->withHeader($name, $value);
         }
     }
     $body = $this->streamFactory->createStream($string);
     $message = $message->withBody($body);
     return $message;
 }
Пример #18
0
 /**
  * Read News Stories
  *
  * @access  public
  * @param   mixed  $input
  * @param   array  $options
  * @throws  RonException
  * @return  array
  */
 public function read($input, array $options = [])
 {
     // Fetch input from a URL
     if ($url = filter_var($input, FILTER_VALIDATE_URL)) {
         if ($this->client === null || $this->message === null) {
             throw new RonException('HttpClient and MessageFactory required to fetch data from a URL');
         }
         try {
             $request = $this->message->createRequest('GET', $url);
             $response = $this->client->sendRequest($request);
             $input = $response->getBody()->getContents();
         } catch (Exception $e) {
             throw new RonException($e->getMessage(), $e->getCode(), $e);
         }
     }
     try {
         $options = array_replace_recursive(['options' => LIBXML_PARSEHUGE | LIBXML_DTDLOAD | LIBXML_NSCLEAN], $options);
         $stories = [];
         $this->parser->extract($input, $options, $stories);
         return $stories;
     } catch (EssenceException $e) {
         throw new RonException($e->getMessage(), $e->getCode(), $e);
     }
 }
 /**
  * Converts a Guzzle response into a PSR response.
  *
  * @param GuzzleResponse $response
  *
  * @return ResponseInterface
  */
 private function createResponse(GuzzleResponse $response)
 {
     $body = $response->getBody();
     return $this->messageFactory->createResponse($response->getStatusCode(), null, $response->getHeaders(), isset($body) ? $body->detach() : null, $response->getProtocolVersion());
 }
Пример #20
0
 /**
  * Return a element for a taxonomy
  *
  * @param string $eventId
  *
  * @return string
  */
 public function getTaxonomy($taxonomyCode)
 {
     $request = $this->messageFactory->createRequest('GET', self::ENDPOINT . '/taxonomy/' . $taxonomyCode . "?fieldset=id,detail");
     $response = $this->httpClient->sendRequest($request);
     return json_decode($response->getBody(), true)['features'];
 }
 /**
  * {@inheritdoc}
  */
 public function createResponse($statusCode = 200, $reasonPhrase = null, $protocolVersion = '1.1', array $headers = [], $body = null)
 {
     return $this->messageFactory->createResponse($statusCode, $reasonPhrase, $protocolVersion, $headers, $body);
 }
Пример #22
0
 /**
  * Returns a ResponseInterface for the given URI/method.
  *
  * @param string|UriInterface $uri    Request URI.
  * @param string              $method HTTP method (Defaults to 'GET').
  *
  * @return ResponseInterface
  */
 protected function getResponse($uri, $method = 'GET')
 {
     $request = $this->messageFactory->createRequest($method, $uri);
     return $this->client->sendRequest($request);
 }
Пример #23
0
 /**
  * Sends a request with any HTTP method.
  *
  * @param string                      $method  HTTP method to use.
  * @param string|UriInterface         $uri
  * @param array                       $headers
  * @param string|StreamInterface|null $body
  *
  * @throws Exception
  *
  * @return ResponseInterface
  */
 public function send($method, $uri, array $headers = [], $body = null)
 {
     return $this->sendRequest($this->messageFactory->createRequest($method, $uri, $headers, $body));
 }
Пример #24
0
 /**
  * Create a request and queue it with the HttpAdapter.
  *
  * @param string              $method
  * @param string|UriInterface $url
  * @param array               $headers
  */
 protected function queueRequest($method, $url, array $headers)
 {
     $this->httpAdapter->invalidate($this->messageFactory->createRequest($method, $url, $headers));
 }