From c74afa4e3350199ee185c1bcc6951b8b58bc6a6f Mon Sep 17 00:00:00 2001 From: Mohammad Haris Date: Thu, 14 Jul 2022 10:16:05 +0500 Subject: [PATCH] Remove static properties and methods from Request.php. (#25) Remove static properties and methods from Unirest and calls from related test cases. --- composer.json | 9 +- src/{Unirest => }/Exception.php | 0 src/{Unirest => }/Method.php | 0 src/{Unirest => }/OverrideRetry.php | 0 src/{Unirest => }/Request.php | 344 ++++++++++++++-------------- src/{Unirest => }/Request/Body.php | 17 +- src/{Unirest => }/Response.php | 0 src/Unirest.php | 7 - tests/Unirest/BodyTest.php | 34 ++- tests/Unirest/RequestChild.php | 8 +- tests/Unirest/RequestTest.php | 183 ++++++++------- tests/Unirest/ResponseTest.php | 18 +- tests/bootstrap.php | 11 +- 13 files changed, 344 insertions(+), 287 deletions(-) rename src/{Unirest => }/Exception.php (100%) rename src/{Unirest => }/Method.php (100%) rename src/{Unirest => }/OverrideRetry.php (100%) rename src/{Unirest => }/Request.php (63%) mode change 100755 => 100644 rename src/{Unirest => }/Request/Body.php (78%) rename src/{Unirest => }/Response.php (100%) delete mode 100644 src/Unirest.php diff --git a/composer.json b/composer.json index fcbf31d..7585abb 100644 --- a/composer.json +++ b/composer.json @@ -33,14 +33,19 @@ "ext-json": "Allows using JSON Bodies for sending and parsing requests" }, "require-dev": { + "squizlabs/php_codesniffer": "^3.0.0", "phpunit/phpunit": "^5 || ^6 || ^7 || ^8 || ^9" }, "autoload": { - "psr-0": { + "psr-4": { "Unirest\\": "src/" } }, + "scripts": { + "test": "phpunit", + "test-coverage": "phpunit --coverage-html=coverage" + }, "support": { "email": "opensource@apimatic.io" } -} \ No newline at end of file +} diff --git a/src/Unirest/Exception.php b/src/Exception.php similarity index 100% rename from src/Unirest/Exception.php rename to src/Exception.php diff --git a/src/Unirest/Method.php b/src/Method.php similarity index 100% rename from src/Unirest/Method.php rename to src/Method.php diff --git a/src/Unirest/OverrideRetry.php b/src/OverrideRetry.php similarity index 100% rename from src/Unirest/OverrideRetry.php rename to src/OverrideRetry.php diff --git a/src/Unirest/Request.php b/src/Request.php old mode 100755 new mode 100644 similarity index 63% rename from src/Unirest/Request.php rename to src/Request.php index d4c399d..efbfefd --- a/src/Unirest/Request.php +++ b/src/Request.php @@ -4,32 +4,32 @@ class Request { - private static $cookie = null; - private static $cookieFile = null; - private static $curlOpts = array(); - private static $handle = null; - private static $jsonOpts = array(); - private static $socketTimeout = null; - private static $enableRetries = false; // should we enable retries feature - private static $maxNumberOfRetries = 3; // total number of allowed retries - private static $retryOnTimeout = false; // Should we retry on timeout? - private static $retryInterval = 1.0; // Initial retry interval in seconds, to be increased by backoffFactor - private static $maximumRetryWaitTime = 120; // maximum retry wait time (commutative) - private static $backoffFactor = 2.0; // backoff factor to be used to increase retry interval - private static $httpStatusCodesToRetry = array(408, 413, 429, 500, 502, 503, 504, 521, 522, 524); - private static $httpMethodsToRetry = array("GET", "PUT"); - private static $overrideRetryForNextRequest = OverrideRetry::USE_GLOBAL_SETTINGS; - private static $verifyPeer = true; - private static $verifyHost = true; - private static $defaultHeaders = array(); - - private static $auth = array ( + private $cookie = null; + private $cookieFile = null; + private $curlOpts = array(); + private $handle = null; + private $jsonOpts = array(); + private $socketTimeout = null; + private $enableRetries = false; // should we enable retries feature + private $maxNumberOfRetries = 3; // total number of allowed retries + private $retryOnTimeout = false; // Should we retry on timeout? + private $retryInterval = 1.0; // Initial retry interval in seconds, to be increased by backoffFactor + private $maximumRetryWaitTime = 120; // maximum retry wait time (commutative) + private $backoffFactor = 2.0; // backoff factor to be used to increase retry interval + private $httpStatusCodesToRetry = array(408, 413, 429, 500, 502, 503, 504, 521, 522, 524); + private $httpMethodsToRetry = array("GET", "PUT"); + private $overrideRetryForNextRequest = OverrideRetry::USE_GLOBAL_SETTINGS; + private $verifyPeer = true; + private $verifyHost = true; + private $defaultHeaders = array(); + + private $auth = array ( 'user' => '', 'pass' => '', 'method' => CURLAUTH_BASIC ); - private static $proxy = array( + private $proxy = array( 'port' => false, 'tunnel' => false, 'address' => false, @@ -41,7 +41,7 @@ class Request ) ); - protected static $totalNumberOfConnections = 0; + protected $totalNumberOfConnections = 0; /** * Set JSON decode mode @@ -51,9 +51,9 @@ class Request * @param integer $options Bitmask of JSON decode options. Currently only JSON_BIGINT_AS_STRING is supported (default is to cast large integers as floats) * @return array */ - public static function jsonOpts($assoc = false, $depth = 512, $options = 0) + public function jsonOpts($assoc = false, $depth = 512, $options = 0) { - return self::$jsonOpts = array($assoc, $depth, $options); + return $this->jsonOpts = array($assoc, $depth, $options); } /** @@ -62,9 +62,9 @@ public static function jsonOpts($assoc = false, $depth = 512, $options = 0) * @param bool $enabled enable SSL verification, by default is true * @return bool */ - public static function verifyPeer($enabled) + public function verifyPeer($enabled) { - return self::$verifyPeer = $enabled; + return $this->verifyPeer = $enabled; } /** @@ -73,9 +73,9 @@ public static function verifyPeer($enabled) * @param bool $enabled enable SSL host verification, by default is true * @return bool */ - public static function verifyHost($enabled) + public function verifyHost($enabled) { - return self::$verifyHost = $enabled; + return $this->verifyHost = $enabled; } /** @@ -84,9 +84,9 @@ public static function verifyHost($enabled) * @param integer $seconds timeout value in seconds * @return integer */ - public static function timeout($seconds) + public function timeout($seconds) { - return self::$socketTimeout = $seconds; + return $this->socketTimeout = $seconds; } /** @@ -95,9 +95,9 @@ public static function timeout($seconds) * @param bool $enableRetries * @return bool */ - public static function enableRetries($enableRetries) + public function enableRetries($enableRetries) { - return self::$enableRetries = $enableRetries; + return $this->enableRetries = $enableRetries; } /** @@ -106,9 +106,9 @@ public static function enableRetries($enableRetries) * @param integer $maxNumberOfRetries * @return integer */ - public static function maxNumberOfRetries($maxNumberOfRetries) + public function maxNumberOfRetries($maxNumberOfRetries) { - return self::$maxNumberOfRetries = $maxNumberOfRetries; + return $this->maxNumberOfRetries = $maxNumberOfRetries; } /** @@ -117,9 +117,9 @@ public static function maxNumberOfRetries($maxNumberOfRetries) * @param bool $retryOnTimeout * @return bool */ - public static function retryOnTimeout($retryOnTimeout) + public function retryOnTimeout($retryOnTimeout) { - return self::$retryOnTimeout = $retryOnTimeout; + return $this->retryOnTimeout = $retryOnTimeout; } /** @@ -128,9 +128,9 @@ public static function retryOnTimeout($retryOnTimeout) * @param float $retryInterval * @return float */ - public static function retryInterval($retryInterval) + public function retryInterval($retryInterval) { - return self::$retryInterval = $retryInterval; + return $this->retryInterval = $retryInterval; } /** @@ -139,9 +139,9 @@ public static function retryInterval($retryInterval) * @param integer $maximumRetryWaitTime * @return integer */ - public static function maximumRetryWaitTime($maximumRetryWaitTime) + public function maximumRetryWaitTime($maximumRetryWaitTime) { - return self::$maximumRetryWaitTime = $maximumRetryWaitTime; + return $this->maximumRetryWaitTime = $maximumRetryWaitTime; } /** @@ -150,9 +150,9 @@ public static function maximumRetryWaitTime($maximumRetryWaitTime) * @param float $backoffFactor * @return float */ - public static function backoffFactor($backoffFactor) + public function backoffFactor($backoffFactor) { - return self::$backoffFactor = $backoffFactor; + return $this->backoffFactor = $backoffFactor; } /** @@ -161,9 +161,9 @@ public static function backoffFactor($backoffFactor) * @param integer[] $httpStatusCodesToRetry * @return integer[] */ - public static function httpStatusCodesToRetry($httpStatusCodesToRetry) + public function httpStatusCodesToRetry($httpStatusCodesToRetry) { - return self::$httpStatusCodesToRetry = $httpStatusCodesToRetry; + return $this->httpStatusCodesToRetry = $httpStatusCodesToRetry; } /** @@ -172,9 +172,9 @@ public static function httpStatusCodesToRetry($httpStatusCodesToRetry) * @param string[] $httpMethodsToRetry * @return string[] */ - public static function httpMethodsToRetry($httpMethodsToRetry) + public function httpMethodsToRetry($httpMethodsToRetry) { - return self::$httpMethodsToRetry = $httpMethodsToRetry; + return $this->httpMethodsToRetry = $httpMethodsToRetry; } /** @@ -183,9 +183,9 @@ public static function httpMethodsToRetry($httpMethodsToRetry) * @param string $overrideRetryForNextRequest * @return string */ - public static function overrideRetryForNextRequest($overrideRetryForNextRequest) + public function overrideRetryForNextRequest($overrideRetryForNextRequest) { - return self::$overrideRetryForNextRequest = $overrideRetryForNextRequest; + return $this->overrideRetryForNextRequest = $overrideRetryForNextRequest; } /** @@ -194,9 +194,9 @@ public static function overrideRetryForNextRequest($overrideRetryForNextRequest) * @param array $headers headers array * @return array */ - public static function defaultHeaders($headers) + public function defaultHeaders($headers) { - return self::$defaultHeaders = array_merge(self::$defaultHeaders, $headers); + return $this->defaultHeaders = array_merge($this->defaultHeaders, $headers); } /** @@ -206,17 +206,17 @@ public static function defaultHeaders($headers) * @param string $value header value * @return string */ - public static function defaultHeader($name, $value) + public function defaultHeader($name, $value) { - return self::$defaultHeaders[$name] = $value; + return $this->defaultHeaders[$name] = $value; } /** * Clear all the default headers */ - public static function clearDefaultHeaders() + public function clearDefaultHeaders() { - return self::$defaultHeaders = array(); + return $this->defaultHeaders = array(); } /** @@ -225,9 +225,9 @@ public static function clearDefaultHeaders() * @param array $options options array * @return array */ - public static function curlOpts($options) + public function curlOpts($options) { - return self::mergeCurlOptions(self::$curlOpts, $options); + return $this->mergeCurlOptions($this->curlOpts, $options); } /** @@ -237,17 +237,17 @@ public static function curlOpts($options) * @param string $value header value * @return string */ - public static function curlOpt($name, $value) + public function curlOpt($name, $value) { - return self::$curlOpts[$name] = $value; + return $this->curlOpts[$name] = $value; } /** * Clear all curl opts */ - public static function clearCurlOpts() + public function clearCurlOpts() { - return self::$curlOpts = array(); + return $this->curlOpts = array(); } /** @@ -260,9 +260,9 @@ public static function clearCurlOpts() * @param string $key Mashape key * @return string */ - public static function setMashapeKey($key) + public function setMashapeKey($key) { - return self::defaultHeader('X-Mashape-Key', $key); + return $this->defaultHeader('X-Mashape-Key', $key); } /** @@ -270,9 +270,9 @@ public static function setMashapeKey($key) * * @param string $cookie */ - public static function cookie($cookie) + public function cookie($cookie) { - self::$cookie = $cookie; + $this->cookie = $cookie; } /** @@ -282,9 +282,9 @@ public static function cookie($cookie) * * @param string $cookieFile - path to file for saving cookie */ - public static function cookieFile($cookieFile) + public function cookieFile($cookieFile) { - self::$cookieFile = $cookieFile; + $this->cookieFile = $cookieFile; } /** @@ -294,11 +294,11 @@ public static function cookieFile($cookieFile) * @param string $password authentication password * @param integer $method authentication method */ - public static function auth($username = '', $password = '', $method = CURLAUTH_BASIC) + public function auth($username = '', $password = '', $method = CURLAUTH_BASIC) { - self::$auth['user'] = $username; - self::$auth['pass'] = $password; - self::$auth['method'] = $method; + $this->auth['user'] = $username; + $this->auth['pass'] = $password; + $this->auth['method'] = $method; } /** @@ -309,12 +309,12 @@ public static function auth($username = '', $password = '', $method = CURLAUTH_B * @param integer $type (Available options for this are CURLPROXY_HTTP, CURLPROXY_HTTP_1_0 CURLPROXY_SOCKS4, CURLPROXY_SOCKS5, CURLPROXY_SOCKS4A and CURLPROXY_SOCKS5_HOSTNAME) * @param bool $tunnel enable/disable tunneling */ - public static function proxy($address, $port = 1080, $type = CURLPROXY_HTTP, $tunnel = false) + public function proxy($address, $port = 1080, $type = CURLPROXY_HTTP, $tunnel = false) { - self::$proxy['type'] = $type; - self::$proxy['port'] = $port; - self::$proxy['tunnel'] = $tunnel; - self::$proxy['address'] = $address; + $this->proxy['type'] = $type; + $this->proxy['port'] = $port; + $this->proxy['tunnel'] = $tunnel; + $this->proxy['address'] = $address; } /** @@ -324,11 +324,11 @@ public static function proxy($address, $port = 1080, $type = CURLPROXY_HTTP, $tu * @param string $password authentication password * @param integer $method authentication method */ - public static function proxyAuth($username = '', $password = '', $method = CURLAUTH_BASIC) + public function proxyAuth($username = '', $password = '', $method = CURLAUTH_BASIC) { - self::$proxy['auth']['user'] = $username; - self::$proxy['auth']['pass'] = $password; - self::$proxy['auth']['method'] = $method; + $this->proxy['auth']['user'] = $username; + $this->proxy['auth']['pass'] = $password; + $this->proxy['auth']['method'] = $method; } /** @@ -341,9 +341,9 @@ public static function proxyAuth($username = '', $password = '', $method = CURLA * @param string $password Authentication password (deprecated) * @return Response */ - public static function get($url, $headers = array(), $parameters = null, $username = null, $password = null) + public function get($url, $headers = array(), $parameters = null, $username = null, $password = null) { - return self::send(Method::GET, $url, $parameters, $headers, $username, $password); + return $this->send(Method::GET, $url, $parameters, $headers, $username, $password); } /** @@ -355,9 +355,9 @@ public static function get($url, $headers = array(), $parameters = null, $userna * @param string $password Basic Authentication password (deprecated) * @return Response */ - public static function head($url, $headers = array(), $parameters = null, $username = null, $password = null) + public function head($url, $headers = array(), $parameters = null, $username = null, $password = null) { - return self::send(Method::HEAD, $url, $parameters, $headers, $username, $password); + return $this->send(Method::HEAD, $url, $parameters, $headers, $username, $password); } /** @@ -369,9 +369,9 @@ public static function head($url, $headers = array(), $parameters = null, $usern * @param string $password Basic Authentication password * @return Response */ - public static function options($url, $headers = array(), $parameters = null, $username = null, $password = null) + public function options($url, $headers = array(), $parameters = null, $username = null, $password = null) { - return self::send(Method::OPTIONS, $url, $parameters, $headers, $username, $password); + return $this->send(Method::OPTIONS, $url, $parameters, $headers, $username, $password); } /** @@ -383,9 +383,9 @@ public static function options($url, $headers = array(), $parameters = null, $us * @param string $password Basic Authentication password (deprecated) * @return Response */ - public static function connect($url, $headers = array(), $parameters = null, $username = null, $password = null) + public function connect($url, $headers = array(), $parameters = null, $username = null, $password = null) { - return self::send(Method::CONNECT, $url, $parameters, $headers, $username, $password); + return $this->send(Method::CONNECT, $url, $parameters, $headers, $username, $password); } /** @@ -397,9 +397,9 @@ public static function connect($url, $headers = array(), $parameters = null, $us * @param string $password Basic Authentication password (deprecated) * @return Response response */ - public static function post($url, $headers = array(), $body = null, $username = null, $password = null) + public function post($url, $headers = array(), $body = null, $username = null, $password = null) { - return self::send(Method::POST, $url, $body, $headers, $username, $password); + return $this->send(Method::POST, $url, $body, $headers, $username, $password); } /** @@ -411,9 +411,9 @@ public static function post($url, $headers = array(), $body = null, $username = * @param string $password Basic Authentication password (deprecated) * @return Response */ - public static function delete($url, $headers = array(), $body = null, $username = null, $password = null) + public function delete($url, $headers = array(), $body = null, $username = null, $password = null) { - return self::send(Method::DELETE, $url, $body, $headers, $username, $password); + return $this->send(Method::DELETE, $url, $body, $headers, $username, $password); } /** @@ -425,9 +425,9 @@ public static function delete($url, $headers = array(), $body = null, $username * @param string $password Basic Authentication password (deprecated) * @return Response */ - public static function put($url, $headers = array(), $body = null, $username = null, $password = null) + public function put($url, $headers = array(), $body = null, $username = null, $password = null) { - return self::send(Method::PUT, $url, $body, $headers, $username, $password); + return $this->send(Method::PUT, $url, $body, $headers, $username, $password); } /** @@ -439,9 +439,9 @@ public static function put($url, $headers = array(), $body = null, $username = n * @param string $password Basic Authentication password (deprecated) * @return Response */ - public static function patch($url, $headers = array(), $body = null, $username = null, $password = null) + public function patch($url, $headers = array(), $body = null, $username = null, $password = null) { - return self::send(Method::PATCH, $url, $body, $headers, $username, $password); + return $this->send(Method::PATCH, $url, $body, $headers, $username, $password); } /** @@ -453,9 +453,9 @@ public static function patch($url, $headers = array(), $body = null, $username = * @param string $password Basic Authentication password (deprecated) * @return Response */ - public static function trace($url, $headers = array(), $body = null, $username = null, $password = null) + public function trace($url, $headers = array(), $body = null, $username = null, $password = null) { - return self::send(Method::TRACE, $url, $body, $headers, $username, $password); + return $this->send(Method::TRACE, $url, $body, $headers, $username, $password); } /** @@ -465,7 +465,7 @@ public static function trace($url, $headers = array(), $body = null, $username = * @param bool|string $parent parent key or false if no parent * @return array */ - public static function buildHTTPCurlQuery($data, $parent = false) + public function buildHTTPCurlQuery($data, $parent = false) { $result = array(); @@ -481,7 +481,7 @@ public static function buildHTTPCurlQuery($data, $parent = false) } if (!$value instanceof \CURLFile and (is_array($value) or is_object($value))) { - $result = array_merge($result, self::buildHTTPCurlQuery($value, $new_key)); + $result = array_merge($result, $this->buildHTTPCurlQuery($value, $new_key)); } else { $result[$new_key] = $value; } @@ -490,10 +490,10 @@ public static function buildHTTPCurlQuery($data, $parent = false) return $result; } - protected static function initializeHandle() + protected function initializeHandle() { - self::$handle = curl_init(); - self::$totalNumberOfConnections = 0; + $this->handle = curl_init(); + $this->totalNumberOfConnections = 0; } /** @@ -507,25 +507,25 @@ protected static function initializeHandle() * @throws \Unirest\Exception if a cURL error occurs * @return Response */ - public static function send($method, $url, $body = null, $headers = array(), $username = null, $password = null) + public function send($method, $url, $body = null, $headers = array(), $username = null, $password = null) { - if (self::$handle == null) { - self::initializeHandle(); + if ($this->handle == null) { + $this->initializeHandle(); } else { - curl_reset(self::$handle); + curl_reset($this->handle); } if ($method !== Method::GET) { if ($method === Method::POST) { - curl_setopt(self::$handle, CURLOPT_POST, true); + curl_setopt($this->handle, CURLOPT_POST, true); } else { if ($method === Method::HEAD) { - curl_setopt(self::$handle, CURLOPT_NOBODY, true); + curl_setopt($this->handle, CURLOPT_NOBODY, true); } - curl_setopt(self::$handle, CURLOPT_CUSTOMREQUEST, $method); + curl_setopt($this->handle, CURLOPT_CUSTOMREQUEST, $method); } - curl_setopt(self::$handle, CURLOPT_POSTFIELDS, $body); + curl_setopt($this->handle, CURLOPT_POSTFIELDS, $body); } elseif (is_array($body)) { if (strpos($url, '?') !== false) { $url .= '&'; @@ -533,96 +533,96 @@ public static function send($method, $url, $body = null, $headers = array(), $us $url .= '?'; } - $url .= urldecode(http_build_query(self::buildHTTPCurlQuery($body))); + $url .= urldecode(http_build_query($this->buildHTTPCurlQuery($body))); } $curl_base_options = [ - CURLOPT_URL => self::validateUrl($url), + CURLOPT_URL => $this->validateUrl($url), CURLOPT_RETURNTRANSFER => true, CURLOPT_FOLLOWLOCATION => true, CURLOPT_MAXREDIRS => 10, - CURLOPT_HTTPHEADER => self::getFormattedHeaders($headers), + CURLOPT_HTTPHEADER => $this->getFormattedHeaders($headers), CURLOPT_HEADER => true, - CURLOPT_SSL_VERIFYPEER => self::$verifyPeer, + CURLOPT_SSL_VERIFYPEER => $this->verifyPeer, //CURLOPT_SSL_VERIFYHOST accepts only 0 (false) or 2 (true). Future versions of libcurl will treat values 1 and 2 as equals - CURLOPT_SSL_VERIFYHOST => self::$verifyHost === false ? 0 : 2, + CURLOPT_SSL_VERIFYHOST => $this->verifyHost === false ? 0 : 2, // If an empty string, '', is set, a header containing all supported encoding types is sent CURLOPT_ENCODING => '' ]; - curl_setopt_array(self::$handle, self::mergeCurlOptions($curl_base_options, self::$curlOpts)); + curl_setopt_array($this->handle, $this->mergeCurlOptions($curl_base_options, $this->curlOpts)); - if (self::$socketTimeout !== null) { - curl_setopt(self::$handle, CURLOPT_TIMEOUT, self::$socketTimeout); + if ($this->socketTimeout !== null) { + curl_setopt($this->handle, CURLOPT_TIMEOUT, $this->socketTimeout); } - if (self::$cookie) { - curl_setopt(self::$handle, CURLOPT_COOKIE, self::$cookie); + if ($this->cookie) { + curl_setopt($this->handle, CURLOPT_COOKIE, $this->cookie); } - if (self::$cookieFile) { - curl_setopt(self::$handle, CURLOPT_COOKIEFILE, self::$cookieFile); - curl_setopt(self::$handle, CURLOPT_COOKIEJAR, self::$cookieFile); + if ($this->cookieFile) { + curl_setopt($this->handle, CURLOPT_COOKIEFILE, $this->cookieFile); + curl_setopt($this->handle, CURLOPT_COOKIEJAR, $this->cookieFile); } // supporting deprecated http auth method if (!empty($username)) { - curl_setopt_array(self::$handle, array( + curl_setopt_array($this->handle, array( CURLOPT_HTTPAUTH => CURLAUTH_BASIC, CURLOPT_USERPWD => $username . ':' . $password )); } - if (!empty(self::$auth['user'])) { - curl_setopt_array(self::$handle, array( - CURLOPT_HTTPAUTH => self::$auth['method'], - CURLOPT_USERPWD => self::$auth['user'] . ':' . self::$auth['pass'] + if (!empty($this->auth['user'])) { + curl_setopt_array($this->handle, array( + CURLOPT_HTTPAUTH => $this->auth['method'], + CURLOPT_USERPWD => $this->auth['user'] . ':' . $this->auth['pass'] )); } - if (self::$proxy['address'] !== false) { - curl_setopt_array(self::$handle, array( - CURLOPT_PROXYTYPE => self::$proxy['type'], - CURLOPT_PROXY => self::$proxy['address'], - CURLOPT_PROXYPORT => self::$proxy['port'], - CURLOPT_HTTPPROXYTUNNEL => self::$proxy['tunnel'], - CURLOPT_PROXYAUTH => self::$proxy['auth']['method'], - CURLOPT_PROXYUSERPWD => self::$proxy['auth']['user'] . ':' . self::$proxy['auth']['pass'] + if ($this->proxy['address'] !== false) { + curl_setopt_array($this->handle, array( + CURLOPT_PROXYTYPE => $this->proxy['type'], + CURLOPT_PROXY => $this->proxy['address'], + CURLOPT_PROXYPORT => $this->proxy['port'], + CURLOPT_HTTPPROXYTUNNEL => $this->proxy['tunnel'], + CURLOPT_PROXYAUTH => $this->proxy['auth']['method'], + CURLOPT_PROXYUSERPWD => $this->proxy['auth']['user'] . ':' . $this->proxy['auth']['pass'] )); } $retryCount = 0; // current retry count $waitTime = 0.0; // wait time in secs before current api call - $allowedWaitTime = self::$maximumRetryWaitTime; // remaining allowed wait time in seconds + $allowedWaitTime = $this->maximumRetryWaitTime; // remaining allowed wait time in seconds $httpCode = null; $headers = array(); do { // If Retrying i.e. retryCount >= 1 if ($retryCount > 0) { - self::sleep($waitTime); + $this->sleep($waitTime); // calculate remaining allowed wait Time $allowedWaitTime -= $waitTime; } // Execution of api call - $response = curl_exec(self::$handle); - $error = curl_error(self::$handle); - $info = self::getInfo(); + $response = curl_exec($this->handle); + $error = curl_error($this->handle); + $info = $this->getInfo(); if (!$error) { $header_size = $info['header_size']; $httpCode = $info['http_code']; - $headers = self::parseHeaders(substr($response, 0, $header_size)); + $headers = $this->parseHeaders(substr($response, 0, $header_size)); } - if (self::shouldRetryRequest($method)) { + if ($this->shouldRetryRequest($method)) { // calculate wait time for retry, and should not retry when wait time becomes 0 - $waitTime = self::getRetryWaitTime($httpCode, $headers, $error, $allowedWaitTime, $retryCount); + $waitTime = $this->getRetryWaitTime($httpCode, $headers, $error, $allowedWaitTime, $retryCount); $retryCount++; } } while ($waitTime > 0.0); // reset request level retries check - self::$overrideRetryForNextRequest = OverrideRetry::USE_GLOBAL_SETTINGS; + $this->overrideRetryForNextRequest = OverrideRetry::USE_GLOBAL_SETTINGS; if ($error) { throw new Exception($error); @@ -630,9 +630,9 @@ public static function send($method, $url, $body = null, $headers = array(), $us // get response body $body = substr($response, $header_size); - self::$totalNumberOfConnections += curl_getinfo(self::$handle, CURLINFO_NUM_CONNECTS); + $this->totalNumberOfConnections += curl_getinfo($this->handle, CURLINFO_NUM_CONNECTS); - return new Response($httpCode, $body, $headers, self::$jsonOpts); + return new Response($httpCode, $body, $headers, $this->jsonOpts); } /** @@ -640,7 +640,7 @@ public static function send($method, $url, $body = null, $headers = array(), $us * * @param $seconds float seconds with upto 6 decimal places, here decimal part will be converted into microseconds */ - private static function sleep($seconds) + private function sleep($seconds) { $secs = (int) $seconds; // the fraction part of the $seconds will always be less than 1 sec, extracting micro seconds @@ -656,13 +656,13 @@ private static function sleep($seconds) * @param $method string|Method HttpMethod of request * @return bool */ - private static function shouldRetryRequest($method) + private function shouldRetryRequest($method) { - switch (self::$overrideRetryForNextRequest) { + switch ($this->overrideRetryForNextRequest) { case OverrideRetry::ENABLE_RETRY: - return self::$enableRetries; + return $this->enableRetries; case OverrideRetry::USE_GLOBAL_SETTINGS: - return self::$enableRetries && in_array($method, self::$httpMethodsToRetry); + return $this->enableRetries && in_array($method, $this->httpMethodsToRetry); case OverrideRetry::DISABLE_RETRY: return false; } @@ -679,26 +679,26 @@ private static function shouldRetryRequest($method) * @param $retryCount int Attempt number * @return float Wait time before sending the next apiCall */ - private static function getRetryWaitTime($httpCode, $headers, $error, $allowedWaitTime, $retryCount) + private function getRetryWaitTime($httpCode, $headers, $error, $allowedWaitTime, $retryCount) { $retryWaitTime = 0.0; $retry_after = 0; if ($error) { - $retry = self::$retryOnTimeout && curl_errno(self::$handle) == CURLE_OPERATION_TIMEDOUT; + $retry = $this->retryOnTimeout && curl_errno($this->handle) == CURLE_OPERATION_TIMEDOUT; } else { // Successful apiCall with some status code or with Retry-After header $headers_lower_keys = array_change_key_case($headers); $retry_after_val = key_exists('retry-after', $headers_lower_keys) ? $headers_lower_keys['retry-after'] : null; - $retry_after = self::getRetryAfterInSeconds($retry_after_val); - $retry = isset($retry_after_val) || in_array($httpCode, self::$httpStatusCodesToRetry); + $retry_after = $this->getRetryAfterInSeconds($retry_after_val); + $retry = isset($retry_after_val) || in_array($httpCode, $this->httpStatusCodesToRetry); } // Calculate wait time only if max number of retries are not already attempted - if ($retry && $retryCount < self::$maxNumberOfRetries) { + if ($retry && $retryCount < $this->maxNumberOfRetries) { // noise between 0 and 0.1 secs upto 6 decimal places $noise = rand(0, 100000) / 1000000; // calculate wait time with exponential backoff and noise in seconds - $waitTime = (self::$retryInterval * pow(self::$backoffFactor, $retryCount)) + $noise; + $waitTime = ($this->retryInterval * pow($this->backoffFactor, $retryCount)) + $noise; // select maximum of waitTime and retry_after $waitTime = floatval(max($waitTime, $retry_after)); if ($waitTime <= $allowedWaitTime) { @@ -716,7 +716,7 @@ private static function getRetryWaitTime($httpCode, $headers, $error, $allowedWa * formatted datetime string * @return int Number of seconds specified by retry-after param */ - private static function getRetryAfterInSeconds($retry_after) + private function getRetryAfterInSeconds($retry_after) { if (isset($retry_after)) { if (is_numeric($retry_after)) { @@ -732,14 +732,14 @@ private static function getRetryAfterInSeconds($retry_after) } /** - * if PECL_HTTP is not available use a fall back function + * if PECL_HTTP is not available use a fallback function * * thanks to ricardovermeltfoort@gmail.com * http://php.net/manual/en/function.http-parse-headers.php#112986 * @param string $raw_headers raw headers * @return array */ - private static function parseHeaders($raw_headers) + private function parseHeaders($raw_headers) { if (function_exists('http_parse_headers')) { return http_parse_headers($raw_headers); @@ -773,30 +773,30 @@ private static function parseHeaders($raw_headers) } } - public static function getInfo($opt = false) + public function getInfo($opt = false) { if ($opt) { - $info = curl_getinfo(self::$handle, $opt); + $info = curl_getinfo($this->handle, $opt); } else { - $info = curl_getinfo(self::$handle); + $info = curl_getinfo($this->handle); } return $info; } - public static function getCurlHandle() + public function getCurlHandle() { - return self::$handle; + return $this->handle; } - public static function getFormattedHeaders($headers) + public function getFormattedHeaders($headers) { $formattedHeaders = array(); - $combinedHeaders = array_change_key_case(array_merge(self::$defaultHeaders, (array) $headers)); + $combinedHeaders = array_change_key_case(array_merge($this->defaultHeaders, (array) $headers)); foreach ($combinedHeaders as $key => $val) { - $formattedHeaders[] = self::getHeaderString($key, $val); + $formattedHeaders[] = $this->getHeaderString($key, $val); } if (!array_key_exists('user-agent', $combinedHeaders)) { @@ -816,7 +816,7 @@ public static function getFormattedHeaders($headers) * @return string Pre-processed Url as string * @throws Exception */ - public static function validateUrl($url) + public function validateUrl($url) { //perform parameter validation if (!is_string($url)) { @@ -838,7 +838,7 @@ public static function validateUrl($url) return $protocol . $query; } - private static function getHeaderString($key, $val) + private function getHeaderString($key, $val) { $key = trim(strtolower($key)); return $key . ': ' . $val; @@ -849,7 +849,7 @@ private static function getHeaderString($key, $val) * @param array $new_options * @return array */ - private static function mergeCurlOptions(&$existing_options, $new_options) + private function mergeCurlOptions(&$existing_options, $new_options) { $existing_options = $new_options + $existing_options; return $existing_options; diff --git a/src/Unirest/Request/Body.php b/src/Request/Body.php similarity index 78% rename from src/Unirest/Request/Body.php rename to src/Request/Body.php index edaeccf..2f9eb6c 100644 --- a/src/Unirest/Request/Body.php +++ b/src/Request/Body.php @@ -7,6 +7,13 @@ class Body { + private $request; + + public function __construct(Request $request) + { + $this->request = $request; + } + /** * Prepares a file for upload. To be used inside the parameters declaration for a request. * @param string $filename The file path @@ -14,7 +21,7 @@ class Body * @param string $postname the file name * @return string|\CURLFile */ - public static function File($filename, $mimetype = '', $postname = '') + public function File($filename, $mimetype = '', $postname = '') { if (class_exists('CURLFile')) { return new \CURLFile($filename, $mimetype, $postname); @@ -27,7 +34,7 @@ public static function File($filename, $mimetype = '', $postname = '') return sprintf('@%s;filename=%s;type=%s', $filename, $postname ?: basename($filename), $mimetype); } - public static function Json($data) + public function Json($data) { if (!function_exists('json_encode')) { throw new Exception('JSON Extension not available'); @@ -36,16 +43,16 @@ public static function Json($data) return json_encode($data); } - public static function Form($data) + public function Form($data) { if (is_array($data) || is_object($data) || $data instanceof \Traversable) { - return http_build_query(Request::buildHTTPCurlQuery($data)); + return http_build_query($this->request->buildHTTPCurlQuery($data)); } return $data; } - public static function Multipart($data, $files = false) + public function Multipart($data, $files = false) { if (is_object($data)) { return get_object_vars($data); diff --git a/src/Unirest/Response.php b/src/Response.php similarity index 100% rename from src/Unirest/Response.php rename to src/Response.php diff --git a/src/Unirest.php b/src/Unirest.php deleted file mode 100644 index 17c72b8..0000000 --- a/src/Unirest.php +++ /dev/null @@ -1,7 +0,0 @@ -request = new Request(); + $this->body = new Body($this->request); + } + public function testCURLFile() { $fixture = __DIR__ . '/fixtures/upload.txt'; - $file = Body::File($fixture); + $file = $this->body->File($fixture); if (PHP_MAJOR_VERSION === 5 && PHP_MINOR_VERSION === 4) { $this->assertEquals($file, sprintf('@%s;filename=%s;type=', $fixture, basename($fixture))); @@ -26,32 +36,32 @@ public function testHttpBuildQueryWithCurlFile() { $fixture = __DIR__ . '/fixtures/upload.txt'; - $file = Body::File($fixture); + $file = $this->body->File($fixture); $body = array( 'to' => 'mail@mailinator.com', 'from' => 'mail@mailinator.com', 'file' => $file ); - $result = Request::buildHTTPCurlQuery($body); + $result = $this->request->buildHTTPCurlQuery($body); $this->assertEquals($result['file'], $file); } public function testJson() { - $body = Body::Json(array('foo', 'bar')); + $body = $this->body->Json(array('foo', 'bar')); $this->assertEquals($body, '["foo","bar"]'); } public function testForm() { - $body = Body::Form(array('foo' => 'bar', 'bar' => 'baz')); + $body = $this->body->Form(array('foo' => 'bar', 'bar' => 'baz')); $this->assertEquals($body, 'foo=bar&bar=baz'); // try again with a string - $body = Body::Form($body); + $body = $this->body->Form($body); $this->assertEquals($body, 'foo=bar&bar=baz'); } @@ -60,11 +70,11 @@ public function testMultipart() { $arr = array('foo' => 'bar', 'bar' => 'baz'); - $body = Body::Multipart((object) $arr); + $body = $this->body->Multipart((object) $arr); $this->assertEquals($body, $arr); - $body = Body::Multipart('flat'); + $body = $this->body->Multipart('flat'); $this->assertEquals($body, array('flat')); } @@ -76,14 +86,14 @@ public function testMultipartFiles() $data = array('foo' => 'bar', 'bar' => 'baz'); $files = array('test' => $fixture); - $body = Body::Multipart($data, $files); + $body = $this->body->Multipart($data, $files); // echo $body; $this->assertEquals($body, array( 'foo' => 'bar', 'bar' => 'baz', - 'test' => Body::File($fixture) + 'test' => $this->body->File($fixture) )); } } diff --git a/tests/Unirest/RequestChild.php b/tests/Unirest/RequestChild.php index 15ef612..ff31fc3 100644 --- a/tests/Unirest/RequestChild.php +++ b/tests/Unirest/RequestChild.php @@ -4,13 +4,13 @@ class RequestChild extends Request { - public static function getTotalNumberOfConnections() + public function getTotalNumberOfConnections() { - return parent::$totalNumberOfConnections; + return $this->totalNumberOfConnections; } - public static function resetHandle() + public function resetHandle() { - parent::initializeHandle(); + $this->initializeHandle(); } } diff --git a/tests/Unirest/RequestTest.php b/tests/Unirest/RequestTest.php index 8895a23..70c720e 100644 --- a/tests/Unirest/RequestTest.php +++ b/tests/Unirest/RequestTest.php @@ -6,33 +6,44 @@ use Unirest\Exception as Exception; use Unirest\RequestChild; -require __DIR__ . '/../../src/Unirest.php'; require __DIR__ . '/RequestChild.php'; class UnirestRequestTest extends \PHPUnit\Framework\TestCase { + private $request; + private $requestChild; + + /** + * @before + */ + public function initializeDependencies() + { + $this->request = new Request(); + $this->requestChild = new RequestChild(); + } + // Generic public function testCurlOpts() { - Request::curlOpt(CURLOPT_COOKIE, 'foo=bar'); + $this->request->curlOpt(CURLOPT_COOKIE, 'foo=bar'); - $response = Request::get('http://mockbin.com/request'); + $response = $this->request->get('http://mockbin.com/request'); $this->assertTrue(property_exists($response->body->cookies, 'foo')); - Request::clearCurlOpts(); + $this->request->clearCurlOpts(); } public function testTimeoutFail() { - Request::timeout(1); + $this->request->timeout(1); $message = "Timeout exception not thrown"; try { - Request::get('http://mockbin.com/delay/2000'); + $this->request->get('http://mockbin.com/delay/2000'); } catch (Exception $e) { $message = substr($e->getMessage(), 0, 19); } - Request::timeout(null); // Cleaning timeout for the other tests + $this->request->timeout(null); // Cleaning timeout for the other tests $this->assertEquals('Operation timed out', $message); } @@ -42,9 +53,9 @@ public function testDefaultHeaders() 'header1' => 'Hello', 'header2' => 'world' ); - Request::defaultHeaders($defaultHeaders); + $this->request->defaultHeaders($defaultHeaders); - $response = Request::get('http://mockbin.com/request'); + $response = $this->request->get('http://mockbin.com/request'); $this->assertEquals(200, $response->code); $this->assertObjectHasAttribute('header1', $response->body->headers); @@ -52,15 +63,15 @@ public function testDefaultHeaders() $this->assertObjectHasAttribute('header2', $response->body->headers); $this->assertEquals('world', $response->body->headers->header2); - $response = Request::get('http://mockbin.com/request', ['header1' => 'Custom value']); + $response = $this->request->get('http://mockbin.com/request', ['header1' => 'Custom value']); $this->assertEquals(200, $response->code); $this->assertObjectHasAttribute('header1', $response->body->headers); $this->assertEquals('Custom value', $response->body->headers->header1); - Request::clearDefaultHeaders(); + $this->request->clearDefaultHeaders(); - $response = Request::get('http://mockbin.com/request'); + $response = $this->request->get('http://mockbin.com/request'); $this->assertEquals(200, $response->code); $this->assertObjectNotHasAttribute('header1', $response->body->headers); @@ -69,17 +80,17 @@ public function testDefaultHeaders() public function testDefaultHeader() { - Request::defaultHeader('Hello', 'custom'); + $this->request->defaultHeader('Hello', 'custom'); - $response = Request::get('http://mockbin.com/request'); + $response = $this->request->get('http://mockbin.com/request'); $this->assertEquals(200, $response->code); $this->assertTrue(property_exists($response->body->headers, 'hello')); $this->assertEquals('custom', $response->body->headers->hello); - Request::clearDefaultHeaders(); + $this->request->clearDefaultHeaders(); - $response = Request::get('http://mockbin.com/request'); + $response = $this->request->get('http://mockbin.com/request'); $this->assertEquals(200, $response->code); $this->assertFalse(property_exists($response->body->headers, 'hello')); @@ -87,78 +98,78 @@ public function testDefaultHeader() public function testConnectionReuse() { - RequestChild::resetHandle(); + $this->requestChild->resetHandle(); $url = "http://httpbin.org/get"; // test client sending keep-alive automatically - $res = Request::get($url); + $res = $this->requestChild->get($url); $this->assertEquals("keep-alive", $res->headers['Connection']); - $this->assertEquals(1, RequestChild::getTotalNumberOfConnections()); + $this->assertEquals(1, $this->requestChild->getTotalNumberOfConnections()); // test closing connection after response is received - $res = Request::get($url, [ 'Connection' => 'close' ]); + $res = $this->requestChild->get($url, [ 'Connection' => 'close' ]); $this->assertEquals("close", $res->headers['Connection']); - $this->assertEquals(1, RequestChild::getTotalNumberOfConnections()); + $this->assertEquals(1, $this->requestChild->getTotalNumberOfConnections()); // test creating a new connection after closing previous one - $res = Request::get($url); + $res = $this->requestChild->get($url); $this->assertEquals("keep-alive", $res->headers['Connection']); - $this->assertEquals(2, RequestChild::getTotalNumberOfConnections()); + $this->assertEquals(2, $this->requestChild->getTotalNumberOfConnections()); // test persisting the new connection - $res = Request::get($url); + $res = $this->requestChild->get($url); $this->assertEquals("keep-alive", $res->headers['Connection']); - $this->assertEquals(2, RequestChild::getTotalNumberOfConnections()); + $this->assertEquals(2, $this->requestChild->getTotalNumberOfConnections()); } public function testConnectionReuseForMultipleDomains() { - RequestChild::resetHandle(); + $this->requestChild->resetHandle(); $url1 = "http://httpbin.org/get"; $url2 = "http://ptsv2.com/t/cedqp-1655183385"; $url3 = "http://en2hoq5smpha9.x.pipedream.net"; $url4 = "http://mockbin.com/request"; - Request::get($url1); - Request::get($url2); - Request::get($url3); + $this->requestChild->get($url1); + $this->requestChild->get($url2); + $this->requestChild->get($url3); // test creating 3 connections by calling 3 domains - $this->assertEquals(3, RequestChild::getTotalNumberOfConnections()); + $this->assertEquals(3, $this->requestChild->getTotalNumberOfConnections()); - Request::get($url1); - Request::get($url2); - Request::get($url3); + $this->requestChild->get($url1); + $this->requestChild->get($url2); + $this->requestChild->get($url3); // test persisting previous 3 connections - $this->assertEquals(3, RequestChild::getTotalNumberOfConnections()); + $this->assertEquals(3, $this->requestChild->getTotalNumberOfConnections()); - Request::get($url1); - Request::get($url2); - Request::get($url3); - Request::get($url4); + $this->requestChild->get($url1); + $this->requestChild->get($url2); + $this->requestChild->get($url3); + $this->requestChild->get($url4); // test adding a new connection by persisting previous ones using a call to another domain - $this->assertEquals(4, RequestChild::getTotalNumberOfConnections()); + $this->assertEquals(4, $this->requestChild->getTotalNumberOfConnections()); } public function testSetMashapeKey() { - Request::setMashapeKey('abcd'); + $this->request->setMashapeKey('abcd'); - $response = Request::get('http://mockbin.com/request'); + $response = $this->request->get('http://mockbin.com/request'); $this->assertEquals(200, $response->code); $this->assertTrue(property_exists($response->body->headers, 'x-mashape-key')); $this->assertEquals('abcd', $response->body->headers->{'x-mashape-key'}); // send another request - $response = Request::get('http://mockbin.com/request'); + $response = $this->request->get('http://mockbin.com/request'); $this->assertEquals(200, $response->code); $this->assertTrue(property_exists($response->body->headers, 'x-mashape-key')); $this->assertEquals('abcd', $response->body->headers->{'x-mashape-key'}); - Request::clearDefaultHeaders(); + $this->request->clearDefaultHeaders(); - $response = Request::get('http://mockbin.com/request'); + $response = $this->request->get('http://mockbin.com/request'); $this->assertEquals(200, $response->code); $this->assertFalse(property_exists($response->body->headers, 'x-mashape-key')); @@ -166,30 +177,30 @@ public function testSetMashapeKey() public function testGzip() { - $response = Request::post('http://mockbin.com/gzip'); + $response = $this->request->post('http://mockbin.com/gzip'); $this->assertEquals('gzip', $response->headers['Content-Encoding']); } public function testBasicAuthenticationDeprecated() { - $response = Request::get('http://mockbin.com/request', array(), array(), 'user', 'password'); + $response = $this->request->get('http://mockbin.com/request', array(), array(), 'user', 'password'); $this->assertEquals('Basic dXNlcjpwYXNzd29yZA==', $response->body->headers->authorization); } public function testBasicAuthentication() { - Request::auth('user', 'password'); + $this->request->auth('user', 'password'); - $response = Request::get('http://mockbin.com/request'); + $response = $this->request->get('http://mockbin.com/request'); $this->assertEquals('Basic dXNlcjpwYXNzd29yZA==', $response->body->headers->authorization); } public function testCustomHeaders() { - $response = Request::get('http://mockbin.com/request', array( + $response = $this->request->get('http://mockbin.com/request', array( 'user-agent' => 'unirest-php', )); @@ -200,7 +211,7 @@ public function testCustomHeaders() // GET public function testGet() { - $response = Request::get('http://mockbin.com/request?name=Mark', array( + $response = $this->request->get('http://mockbin.com/request?name=Mark', array( 'Accept' => 'application/json' ), array( 'nick' => 'thefosk' @@ -214,7 +225,7 @@ public function testGet() public function testGetMultidimensionalArray() { - $response = Request::get('http://mockbin.com/request', array( + $response = $this->request->get('http://mockbin.com/request', array( 'Accept' => 'application/json' ), array( 'key' => 'value', @@ -233,7 +244,7 @@ public function testGetMultidimensionalArray() public function testGetWithDots() { - $response = Request::get('http://mockbin.com/request', array( + $response = $this->request->get('http://mockbin.com/request', array( 'Accept' => 'application/json' ), array( 'user.name' => 'Mark', @@ -248,7 +259,7 @@ public function testGetWithDots() public function testGetWithDotsAlt() { - $response = Request::get('http://mockbin.com/request', array( + $response = $this->request->get('http://mockbin.com/request', array( 'Accept' => 'application/json' ), array( 'user.name' => 'Mark Bond', @@ -262,7 +273,7 @@ public function testGetWithDotsAlt() } public function testGetWithEqualSign() { - $response = Request::get('http://mockbin.com/request', array( + $response = $this->request->get('http://mockbin.com/request', array( 'Accept' => 'application/json' ), array( 'name' => 'Mark=Hello' @@ -275,7 +286,7 @@ public function testGetWithEqualSign() public function testGetWithEqualSignAlt() { - $response = Request::get('http://mockbin.com/request', array( + $response = $this->request->get('http://mockbin.com/request', array( 'Accept' => 'application/json' ), array( 'name' => 'Mark=Hello=John' @@ -288,7 +299,7 @@ public function testGetWithEqualSignAlt() public function testGetWithComplexQuery() { - $response = Request::get('http://mockbin.com/request?query=[{"type":"/music/album","name":null,"artist":{"id":"/en/bob_dylan"},"limit":3}]&cursor'); + $response = $this->request->get('http://mockbin.com/request?query=[{"type":"/music/album","name":null,"artist":{"id":"/en/bob_dylan"},"limit":3}]&cursor'); $this->assertEquals(200, $response->code); $this->assertEquals('GET', $response->body->method); @@ -298,7 +309,7 @@ public function testGetWithComplexQuery() public function testGetArray() { - $response = Request::get('http://mockbin.com/request', array(), array( + $response = $this->request->get('http://mockbin.com/request', array(), array( 'name[0]' => 'Mark', 'name[1]' => 'John' )); @@ -312,7 +323,7 @@ public function testGetArray() // HEAD public function testHead() { - $response = Request::head('http://mockbin.com/request?name=Mark', array( + $response = $this->request->head('http://mockbin.com/request?name=Mark', array( 'Accept' => 'application/json' )); @@ -322,7 +333,7 @@ public function testHead() // POST public function testPost() { - $response = Request::post('http://mockbin.com/request', array( + $response = $this->request->post('http://mockbin.com/request', array( 'Accept' => 'application/json' ), array( 'name' => 'Mark', @@ -337,12 +348,14 @@ public function testPost() public function testPostForm() { - $body = Request\Body::Form(array( + $bodyObj = new Request\Body($this->request); + + $body = $bodyObj->Form(array( 'name' => 'Mark', 'nick' => 'thefosk' )); - $response = Request::post('http://mockbin.com/request', array( + $response = $this->request->post('http://mockbin.com/request', array( 'Accept' => 'application/json' ), $body); @@ -355,12 +368,14 @@ public function testPostForm() public function testPostMultipart() { - $body = Request\Body::Multipart(array( + $bodyObj = new Request\Body($this->request); + + $body = $bodyObj->Multipart(array( 'name' => 'Mark', 'nick' => 'thefosk' )); - $response = Request::post('http://mockbin.com/request', (object) array( + $response = $this->request->post('http://mockbin.com/request', (object) array( 'Accept' => 'application/json', ), $body); @@ -373,11 +388,13 @@ public function testPostMultipart() public function testPostWithEqualSign() { - $body = Request\Body::Form(array( + $bodyObj = new Request\Body($this->request); + + $body = $bodyObj->Form(array( 'name' => 'Mark=Hello' )); - $response = Request::post('http://mockbin.com/request', array( + $response = $this->request->post('http://mockbin.com/request', array( 'Accept' => 'application/json' ), $body); @@ -388,7 +405,7 @@ public function testPostWithEqualSign() public function testPostArray() { - $response = Request::post('http://mockbin.com/request', array( + $response = $this->request->post('http://mockbin.com/request', array( 'Accept' => 'application/json' ), array( 'name[0]' => 'Mark', @@ -403,7 +420,7 @@ public function testPostArray() public function testPostWithDots() { - $response = Request::post('http://mockbin.com/request', array( + $response = $this->request->post('http://mockbin.com/request', array( 'Accept' => 'application/json' ), array( 'user.name' => 'Mark', @@ -418,7 +435,7 @@ public function testPostWithDots() public function testRawPost() { - $response = Request::post('http://mockbin.com/request', array( + $response = $this->request->post('http://mockbin.com/request', array( 'Accept' => 'application/json', 'Content-Type' => 'application/json' ), json_encode(array( @@ -432,7 +449,9 @@ public function testRawPost() public function testPostMultidimensionalArray() { - $body = Request\Body::Form(array( + $bodyObj = new Request\Body($this->request); + + $body = $bodyObj->Form(array( 'key' => 'value', 'items' => array( 'item1', @@ -440,7 +459,7 @@ public function testPostMultidimensionalArray() ) )); - $response = Request::post('http://mockbin.com/request', array( + $response = $this->request->post('http://mockbin.com/request', array( 'Accept' => 'application/json' ), $body); @@ -454,7 +473,7 @@ public function testPostMultidimensionalArray() // PUT public function testPut() { - $response = Request::put('http://mockbin.com/request', array( + $response = $this->request->put('http://mockbin.com/request', array( 'Accept' => 'application/json' ), array( 'name' => 'Mark', @@ -470,7 +489,7 @@ public function testPut() // PATCH public function testPatch() { - $response = Request::patch('http://mockbin.com/request', array( + $response = $this->request->patch('http://mockbin.com/request', array( 'Accept' => 'application/json' ), array( 'name' => 'Mark', @@ -486,7 +505,7 @@ public function testPatch() // DELETE public function testDelete() { - $response = Request::delete('http://mockbin.com/request', array( + $response = $this->request->delete('http://mockbin.com/request', array( 'Accept' => 'application/json', 'Content-Type' => 'application/x-www-form-urlencoded' ), array( @@ -507,9 +526,11 @@ public function testUpload() $files = array('file' => $fixture); $data = array('name' => 'ahmad'); - $body = Request\Body::Multipart($data, $files); + $bodyObj = new Request\Body($this->request); + + $body = $bodyObj->Multipart($data, $files); - $response = Request::post('http://mockbin.com/request', $headers, $body); + $response = $this->request->post('http://mockbin.com/request', $headers, $body); $this->assertEquals(200, $response->code); $this->assertEquals('POST', $response->body->method); @@ -521,11 +542,13 @@ public function testUploadWithoutHelper() { $fixture = __DIR__ . '/../fixtures/upload.txt'; - $response = Request::post('http://mockbin.com/request', array( + $bodyObj = new Request\Body($this->request); + + $response = $this->request->post('http://mockbin.com/request', array( 'Accept' => 'application/json' ), array( 'name' => 'Mark', - 'file' => Request\Body::File($fixture) + 'file' => $bodyObj->File($fixture) )); $this->assertEquals(200, $response->code); @@ -538,11 +561,13 @@ public function testUploadIfFilePartOfData() { $fixture = __DIR__ . '/../fixtures/upload.txt'; - $response = Request::post('http://mockbin.com/request', array( + $bodyObj = new Request\Body($this->request); + + $response = $this->request->post('http://mockbin.com/request', array( 'Accept' => 'application/json' ), array( 'name' => 'Mark', - 'files[owl.gif]' => Request\Body::File($fixture) + 'files[owl.gif]' => $bodyObj->File($fixture) )); $this->assertEquals(200, $response->code); diff --git a/tests/Unirest/ResponseTest.php b/tests/Unirest/ResponseTest.php index cb7fa97..47d9226 100644 --- a/tests/Unirest/ResponseTest.php +++ b/tests/Unirest/ResponseTest.php @@ -5,13 +5,21 @@ use Unirest\Request as Request; use Unirest\Response as Response; -require __DIR__ . '/../../src/Unirest.php'; - class UnirestResponseTest extends \PHPUnit\Framework\TestCase { + private $request; + + /** + * @before + */ + public function initializeDependencies() + { + $this->request = new Request(); + } + public function testJSONAssociativeArrays() { - $opts = Request::jsonOpts(true); + $opts = $this->request->jsonOpts(true); $response = new Response(200, '{"a":1,"b":2,"c":3,"d":4,"e":5}', '', $opts); $this->assertEquals($response->body['a'], 1); @@ -19,7 +27,7 @@ public function testJSONAssociativeArrays() public function testJSONAObjects() { - $opts = Request::jsonOpts(false); + $opts = $this->request->jsonOpts(false); $response = new Response(200, '{"a":1,"b":2,"c":3,"d":4,"e":5}', '', $opts); $this->assertEquals($response->body->a, 1); @@ -27,7 +35,7 @@ public function testJSONAObjects() public function testJSONOpts() { - $opts = Request::jsonOpts(false, 512, JSON_NUMERIC_CHECK); + $opts = $this->request->jsonOpts(false, 512, JSON_NUMERIC_CHECK); $response = new Response(200, '{"number": 1234567890}', '', $opts); $this->assertSame($response->body->number, 1234567890); diff --git a/tests/bootstrap.php b/tests/bootstrap.php index 7ccbe49..3c4e14f 100644 --- a/tests/bootstrap.php +++ b/tests/bootstrap.php @@ -1 +1,10 @@ - +