Example #1
1
 /**
  * @param Request  $request
  * @param Response $response
  * @throws SurvariumException
  */
 public function __construct(Request $request, Response $response)
 {
     if (!extension_loaded('curl')) {
         throw new SurvariumException('You should install curl extension');
     }
     $this->curl = curl_init();
     $this->request = $request;
     $this->response = $response;
     $this->setOptions($request->getRequestUrl(), $request->getHeaders(), $request->getHttpMethod());
 }
Example #2
0
 /**
  * Construct response object from Request
  *
  * @param   Request $request
  * @access    public
  * @throws  \RuntimeException
  */
 public function __construct(Request $request)
 {
     $options = $request->getOptions();
     $headers = $request->getHeaders();
     if (!isset($options[CURLOPT_URL])) {
         throw new \RuntimeException("the URL for the request is not set");
     }
     $handle = curl_init();
     if (!$handle) {
         throw new \RuntimeException("failed to initialized cURL");
     }
     foreach ($options as $option => $value) {
         if ($option) {
             if (!curl_setopt($handle, $option, $value)) {
                 throw new \RuntimeException("failed to set option {$option} => {$value}");
             }
         }
     }
     if (count($headers)) {
         if (!curl_setopt($handle, CURLOPT_HTTPHEADER, $headers)) {
             throw new \RuntimeException("malformed headers collection");
         }
     }
     $this->data = curl_exec($handle);
     $this->error = ["errno" => curl_errno($handle), "error" => curl_error($handle)];
     if ($this->error["errno"]) {
         throw new \RuntimeException("failed to execute request for {$options[CURLOPT_URL]}", $this->error["errno"]);
     }
     $this->info = curl_getinfo($handle);
     curl_close($handle);
 }
 public function sign(Request $request)
 {
     $currentHeaders = $request->getHeaders();
     $signatureHeader = $this->getV1SignatureHeader($this->credentials->getPublicId(), base64_decode($this->credentials->getSecret()));
     $currentHeaders['x-signature'] = $signatureHeader;
     return new ApiRequest($request->getBaseUrl(), $request->getFunction(), $request->getUrlParams(), $request->getMethod(), $request->getParams(), $currentHeaders);
 }
Example #4
0
 /**
  * @param Request $request
  * @return Response
  */
 public function call(Request $request)
 {
     // Create cURL
     $ch = curl_init();
     // Set-up URL
     curl_setopt($ch, CURLOPT_URL, $request->getUrl());
     // Set-up headers
     $headers = $request->getHeaders();
     array_walk($headers, function (&$item, $key) {
         $item = "{$key}: {$item}";
     });
     curl_setopt($ch, CURLOPT_HTTPHEADER, array_values($headers));
     // Set-up others
     curl_setopt_array($ch, $request->getOpts());
     // Receive result
     $result = curl_exec($ch);
     // Parse response
     $response = new Response();
     if ($result === FALSE) {
         $response->setError(curl_strerror(curl_errno($ch)));
         $response->setData(FALSE);
         $response->setCode(curl_errno($ch));
         $response->setHeaders(curl_getinfo($ch));
     } else {
         $response->setData(json_decode($result));
         $response->setCode(curl_getinfo($ch, CURLINFO_HTTP_CODE));
         $response->setHeaders(curl_getinfo($ch));
     }
     // Close cURL
     curl_close($ch);
     return $response;
 }
 public function send(Request $request)
 {
     $functionUrl = $request->getBaseUrl() . '/' . $request->getFunction();
     if (count($request->getUrlParams()) > 0) {
         $finalUrl = $functionUrl . '?' . http_build_query($request->getUrlParams());
     } else {
         $finalUrl = $functionUrl;
     }
     $ch = curl_init($finalUrl);
     $headerArray = [];
     foreach ($request->getHeaders() as $key => $value) {
         $headerArray[] = ucfirst($key) . ': ' . $value;
     }
     curl_setopt($ch, CURLOPT_HTTPHEADER, $headerArray);
     curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
     $method = strtoupper($request->getMethod());
     switch ($method) {
         case "GET":
             break;
         case "POST":
             curl_setopt($ch, CURLOPT_POST, 1);
             curl_setopt($ch, CURLOPT_POSTFIELDS, $request->getParams());
             break;
         case "DELETE":
             curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "DELETE");
             break;
         case "PUT":
             curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "PUT");
             curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($request->getParams()));
             break;
     }
     return json_decode(curl_exec($ch));
 }
Example #6
0
 function testConstruct()
 {
     $request = new Request('GET', '/foo', ['User-Agent' => 'Evert']);
     $this->assertEquals('GET', $request->getMethod());
     $this->assertEquals('/foo', $request->getUrl());
     $this->assertEquals(['User-Agent' => ['Evert']], $request->getHeaders());
 }
Example #7
0
 public function getHeaders()
 {
     $headers = parent::getHeaders();
     if ($this->isMultipart()) {
         $headers[] = 'Content-Type: multipart/form-data; boundary=' . $this->getBoundary();
     } else {
         $headers[] = 'Content-Type: application/x-www-form-urlencoded';
     }
     return $headers;
 }
Example #8
0
 /**
  * Returns true if the headers of both specified requests match.
  *
  * @param  Request $first  First request to match.
  * @param  Request $second Second request to match.
  *
  * @return boolean True if the headers of both specified requests match.
  */
 public static function matchHeaders(Request $first, Request $second)
 {
     $firstHeaders = $first->getHeaders();
     foreach ($second->getHeaders() as $key => $pattern) {
         if (!isset($firstHeaders[$key]) || $pattern !== $firstHeaders[$key]) {
             return false;
         }
     }
     return true;
 }
 /**
  * Verify basic functionality of the request object.
  *
  * @test
  * @covers ::__construct
  * @covers ::getUrl
  * @covers ::getBody
  * @covers ::getMethod
  * @covers ::getHeaders
  *
  * @return void
  */
 public function construct()
 {
     $url = 'a url';
     $method = 'a method';
     $body = ['some' => 'data'];
     $headers = ['key' => 'value'];
     $request = new Request($url, $method, $headers, $body);
     $this->assertSame($url, $request->getUrl());
     $this->assertSame($method, $request->getMethod());
     $this->assertSame($headers, $request->getHeaders());
     $this->assertSame($body, $request->getBody());
 }
 /**
  * @return Response
  *
  * @throws BadResponseException
  */
 protected function process(Request $request)
 {
     $headerStr = [];
     foreach ($request->getHeaders() as $name => $value) {
         foreach ((array) $value as $v) {
             $headerStr[] = "{$name}: {$v}";
         }
     }
     $options = ['http' => ['method' => $request->getMethod(), 'header' => implode("\r\n", $headerStr) . "\r\n", 'follow_location' => 0, 'protocol_version' => 1.1, 'ignore_errors' => TRUE], 'ssl' => ['verify_peer' => TRUE, 'cafile' => realpath(__DIR__ . '/../../ca-chain.crt'), 'disable_compression' => TRUE]];
     if (($content = $request->getContent()) !== NULL) {
         $options['http']['content'] = $content;
     }
     if ($this->sslOptions) {
         $options['ssl'] = $this->sslOptions + $options['ssl'];
     }
     list($code, $headers, $content) = $this->fileGetContents($request->getUrl(), $options);
     return new Response($code, $headers, $content);
 }
Example #11
0
 /**
  * HTTP POST METHOD (static)
  *
  * @param  string $url
  * @param  array $params
  * @param  array $headers
  * @param  mixed $body
  * @throws Exception\InvalidArgumentException
  * @return Response|bool
  */
 public static function post($url, $params, $headers = array(), $body = null)
 {
     if (empty($url)) {
         return false;
     }
     $request = new Request();
     $request->setUri($url);
     $request->setMethod(Request::METHOD_POST);
     if (!empty($params) && is_array($params)) {
         $request->getPost()->fromArray($params);
     } else {
         throw new Exception\InvalidArgumentException('The array of post parameters is empty');
     }
     if (!isset($headers['Content-Type'])) {
         $headers['Content-Type'] = Client::ENC_URLENCODED;
     }
     if (!empty($headers) && is_array($headers)) {
         $request->getHeaders()->addHeaders($headers);
     }
     if (!empty($body)) {
         $request->setContent($body);
     }
     return static::getStaticClient()->send($request);
 }
Example #12
0
 /**
  * Returns true if the headers of both specified requests match.
  *
  * @param  Request $first  First request to match.
  * @param  Request $second Second request to match.
  *
  * @return boolean True if the headers of both specified requests match.
  */
 public static function matchHeaders(Request $first, Request $second)
 {
     // Use array_filter to ignore headers which are null.
     return array_filter($first->getHeaders()) === array_filter($second->getHeaders());
 }
Example #13
0
 /**
  * {@inheritdoc}
  */
 public function encodeRequest(Request $request) : string
 {
     return sprintf("%s %s HTTP/%s\r\n%s\r\n", $request->getMethod(), $request->getRequestTarget(), $request->getProtocolVersion(), $this->encodeHeaders($request->getHeaders()));
 }
Example #14
0
 /**
  * Helper function to gather all the curl options: global, inferred, and per request
  *
  * @param Request $request
  * @return array
  */
 private function prepareRequestOptions(Request $request)
 {
     // options for this entire curl object
     $options = $this->getOptions();
     // set the request URL
     $options[CURLOPT_URL] = $request->getUrl();
     // set the request method
     $options[CURLOPT_CUSTOMREQUEST] = $request->getMethod();
     // posting data w/ this request?
     if ($request->getPostData()) {
         $options[CURLOPT_POST] = 1;
         $options[CURLOPT_POSTFIELDS] = $request->getPostData();
     }
     // if the request has headers, use those, or if there are global headers, use those
     if ($request->getHeaders()) {
         $options[CURLOPT_HEADER] = 0;
         $options[CURLOPT_HTTPHEADER] = $request->getHeaders();
     } elseif ($this->getHeaders()) {
         $options[CURLOPT_HEADER] = 0;
         $options[CURLOPT_HTTPHEADER] = $this->getHeaders();
     }
     // if the request has options set, use those and have them take precedence
     if ($request->getOptions()) {
         $options = $request->getOptions() + $options;
     }
     return $options;
 }
Example #15
0
 public function testGetHeaders()
 {
     $request = new Request('http://google.com', 'GET');
     $request->setHeader('foo', 'bar');
     $request->setHeader('foo2', array('bar', 'bar2'));
     $this->assertEquals(array('foo: bar', 'foo2: bar,bar2'), $request->getHeaders());
 }
 /**
  * Tests that the overriding of existing headers works as expected.
  */
 public function testReplaceHeader()
 {
     $request = new Request('127.0.0.1');
     $request->setHeader('Foo: bar', 'Bar: baz');
     $request->replaceHeader('Foo', 'baz');
     $this->assertEquals(array('Foo: baz', 'Bar: baz'), $request->getHeaders());
     $request->replaceHeader('Bar', 'foo');
     $this->assertEquals(array('Foo: baz', 'Bar: foo'), $request->getHeaders());
     // Only the first matching instance of a header will be replaced
     $request->setHeader('Baz: asdf', 'Baz: 1234');
     $request->replaceHeader('Baz', 'qwerty');
     $this->assertEquals(array('Foo: baz', 'Bar: foo', 'Baz: qwerty', 'Baz: 1234'), $request->getHeaders());
     // Case sensitivity is not required
     $request->replaceHeader('foo', 'Bar');
     $this->assertEquals(array('foo: Bar', 'Bar: foo', 'Baz: qwerty', 'Baz: 1234'), $request->getHeaders());
     // If the header isn't there yet, it is added
     $request->replaceHeader('Brule', 'Dingus');
     $this->assertEquals(array('foo: Bar', 'Bar: foo', 'Baz: qwerty', 'Baz: 1234', 'Brule: Dingus'), $request->getHeaders());
 }
Example #17
0
 /**
  * @param Request $request
  * @param bool $redirectsEnabled
  * @param int $maxRedirects
  * @return Response
  * @throws RequestException
  */
 public function send(Request $request, $redirectsEnabled = false, $maxRedirects = 20)
 {
     /// Is there curl_init function
     if (!function_exists('curl_init')) {
         throw new RequestException('curl_init doesn\'t exists. Is curl extension instaled and enabled?');
     }
     /// Dont send request without url
     if (!$request->getUrl()) {
         return new Response();
     }
     $url = $request->getUrl();
     if (!empty($this->params)) {
         $url .= '?' . http_build_query($this->params);
     }
     @curl_setopt($this->handle, CURLOPT_URL, $url);
     if ($request->getJSON() !== null) {
         $request->addHeaders(array('Content-Type' => 'application/json'));
     }
     $this->setCookies($request->getCookies());
     $this->setHeaders($request->getHeaders());
     $this->setMethod($request->getMethod());
     /// Set post fields to CURL handle
     if (count($request->getPostFields()) > 0 || $request->getJSON()) {
         $fields = $request->getJSON() ? json_encode($request->getJSON()) : $request->getPostFields();
         $this->setPostFields($fields, $request->getMethod(), $request->getHeader('Content-Type'));
         $request->setJSON(null);
     }
     /// Execute
     $response = curl_exec($this->handle);
     /// Remove content type header to not be used in further requests
     $request->unsetHeader('Content-Type');
     /// Handle CURL error
     if ($response == FALSE) {
         throw new RequestException("CURL error [" . curl_errno($this->handle) . "]: " . curl_error($this->handle), curl_errno($this->handle));
     }
     /// Separate response header and body
     /// Http 100 workaround
     $parts = explode("\r\n\r\nHTTP/", $response);
     $parts = (count($parts) > 1 ? 'HTTP/' : '') . array_pop($parts);
     list($headers, $body) = explode("\r\n\r\n", $parts, 2);
     $response = new Response(curl_getinfo($this->handle, CURLINFO_HTTP_CODE), $headers, $body);
     /// If cookiesEnabled then call addCookies with response cookies
     if ($request->isCookiesEnabled()) {
         $request->addCookies($response->getCookies());
     }
     /// Are redirects enabled? (Also check redirects count)
     if ($redirectsEnabled && ($response->getCode() == 301 || $response->getCode() == 302 || $response->getCode() == 303) && $this->redirectCount < $maxRedirects) {
         $response = $this->doFollow($request, $response, $maxRedirects);
     } else {
         if ($this->redirectCount == $maxRedirects) {
             throw new RequestException("Maximum of " . $maxRedirects . " redirects reached.");
         }
         $this->redirectCount = 0;
     }
     return $response;
 }
Example #18
0
 public function testConstructHeaders()
 {
     $request = new Request("http://www.fabysdev.com", "get", null, ["test" => ["value"]]);
     $this->assertEquals(["test" => ["value"]], $request->getHeaders());
 }