From 6e615557cc2985d260d60234ca400b57b4b5c308 Mon Sep 17 00:00:00 2001 From: Ahmad Nassri Date: Wed, 17 Dec 2014 18:51:36 -0500 Subject: [PATCH 01/41] fixes #24 allows for an extra param to decode json objects into associative arrays --- lib/Unirest/HttpResponse.php | 24 ++++++++++++------------ 1 file changed, 12 insertions(+), 12 deletions(-) diff --git a/lib/Unirest/HttpResponse.php b/lib/Unirest/HttpResponse.php index ea3102e..93a78e8 100644 --- a/lib/Unirest/HttpResponse.php +++ b/lib/Unirest/HttpResponse.php @@ -4,30 +4,30 @@ namespace Unirest; class HttpResponse { - + private $code; private $raw_body; private $body; private $headers; - + /** * @param int $code response code of the cURL request * @param string $raw_body the raw body of the cURL response * @param string $headers raw header string from cURL response */ - public function __construct($code, $raw_body, $headers) + public function __construct($code, $raw_body, $headers, $json_decode_assoc = false) { $this->code = $code; $this->headers = $this->get_headers_from_curl_response($headers); $this->raw_body = $raw_body; $this->body = $raw_body; - $json = json_decode($raw_body); - + $json = json_decode($raw_body, $json_decode_assoc); + if (json_last_error() == JSON_ERROR_NONE) { $this->body = $json; } } - + /** * Return a property of the response if it exists. * Possibilities include: code, raw_body, headers, body (if the response is json-decodable) @@ -39,7 +39,7 @@ class HttpResponse return $this->$property; } } - + /** * Set the properties of this object * @param string $property the property name @@ -52,7 +52,7 @@ class HttpResponse } return $this; } - + /** * Retrieve the cURL response headers from the * header string and convert it into an array @@ -63,15 +63,15 @@ class HttpResponse { $headers = explode("\r\n", $headers); array_shift($headers); - + foreach ($headers as $line) { if (strstr($line, ': ')) { list($key, $value) = explode(': ', $line); $result[$key] = $value; } } - + return $result; } - -} \ No newline at end of file + +} From 2bd214f2d9bf37d1cad763ed55682d79f72addfc Mon Sep 17 00:00:00 2001 From: Ahmad Nassri Date: Wed, 17 Dec 2014 18:54:05 -0500 Subject: [PATCH 02/41] pass additional params to request method to ask for associative json objects --- lib/Unirest/Unirest.php | 78 ++++++++++++++++++++--------------------- 1 file changed, 39 insertions(+), 39 deletions(-) diff --git a/lib/Unirest/Unirest.php b/lib/Unirest/Unirest.php index 8cb109e..ff96d7f 100644 --- a/lib/Unirest/Unirest.php +++ b/lib/Unirest/Unirest.php @@ -5,11 +5,11 @@ use Unirest\HttpResponse; class Unirest { - + private static $verifyPeer = true; private static $socketTimeout = null; private static $defaultHeaders = array(); - + /** * Verify SSL peer * @param bool $enabled enable SSL verification, by default is true @@ -18,7 +18,7 @@ class Unirest { Unirest::$verifyPeer = $enabled; } - + /** * Set a timeout * @param integer $seconds timeout value in seconds @@ -27,7 +27,7 @@ class Unirest { Unirest::$socketTimeout = $seconds; } - + /** * Set a new default header to send on every request * @param string $name header name @@ -37,7 +37,7 @@ class Unirest { Unirest::$defaultHeaders[$name] = $value; } - + /** * Clear all the default headers */ @@ -45,7 +45,7 @@ class Unirest { Unirest::$defaultHeaders = array(); } - + /** * Send a GET request to a URL * @param string $url URL to send the GET request to @@ -59,7 +59,7 @@ class Unirest { return Unirest::request(HttpMethod::GET, $url, $parameters, $headers, $username, $password); } - + /** * Send POST request to a URL * @param string $url URL to send the POST request to @@ -73,7 +73,7 @@ class Unirest { return Unirest::request(HttpMethod::POST, $url, $body, $headers, $username, $password); } - + /** * Send DELETE request to a URL * @param string $url URL to send the DELETE request to @@ -87,7 +87,7 @@ class Unirest { return Unirest::request(HttpMethod::DELETE, $url, $body, $headers, $username, $password); } - + /** * Send PUT request to a URL * @param string $url URL to send the PUT request to @@ -101,7 +101,7 @@ class Unirest { return Unirest::request(HttpMethod::PUT, $url, $body, $headers, $username, $password); } - + /** * Send PATCH request to a URL * @param string $url URL to send the PATCH request to @@ -115,7 +115,7 @@ class Unirest { return Unirest::request(HttpMethod::PATCH, $url, $body, $headers, $username, $password); } - + /** * Prepares a file for upload. To be used inside the parameters declaration for a request. * @param string $path The file path @@ -128,7 +128,7 @@ class Unirest return "@" . $path; } } - + /** * This function is useful for serializing multidimensional arrays, and avoid getting * the "Array to string conversion" notice @@ -138,7 +138,7 @@ class Unirest if (is_object($arrays)) { $arrays = get_object_vars($arrays); } - + foreach ($arrays AS $key => $value) { $k = isset($prefix) ? $prefix . '[' . $key . ']' : $key; if (!$value instanceof \CURLFile AND (is_array($value) OR is_object($value))) { @@ -148,7 +148,7 @@ class Unirest } } } - + /** * Send a cURL request * @param string $httpMethod HTTP method to use (based off \Unirest\HttpMethod constants) @@ -160,7 +160,7 @@ class Unirest * @throws Exception if a cURL error occurs * @return HttpResponse */ - private static function request($httpMethod, $url, $body = NULL, $headers = array(), $username = NULL, $password = NULL) + private static function request($httpMethod, $url, $body = NULL, $headers = array(), $username = NULL, $password = NULL, $json_decode_assoc = false) { if ($headers == NULL) $headers = array(); @@ -170,7 +170,7 @@ class Unirest foreach ($finalHeaders as $key => $val) { $lowercaseHeaders[] = Unirest::getHeader($key, $val); } - + $lowerCaseFinalHeaders = array_change_key_case($finalHeaders); if (!array_key_exists("user-agent", $lowerCaseFinalHeaders)) { $lowercaseHeaders[] = "user-agent: unirest-php/1.1"; @@ -178,7 +178,7 @@ class Unirest if (!array_key_exists("expect", $lowerCaseFinalHeaders)) { $lowercaseHeaders[] = "expect:"; } - + $ch = curl_init(); if ($httpMethod != HttpMethod::GET) { curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $httpMethod); @@ -197,7 +197,7 @@ class Unirest Unirest::http_build_query_for_curl($body, $postBody); $url .= urldecode(http_build_query($postBody)); } - + curl_setopt($ch, CURLOPT_URL, Unirest::encodeUrl($url)); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true); @@ -212,23 +212,23 @@ class Unirest if (!empty($username)) { curl_setopt($ch, CURLOPT_USERPWD, $username . ":" . ((empty($password)) ? "" : $password)); } - + $response = curl_exec($ch); $error = curl_error($ch); if ($error) { throw new Exception($error); } - + // Split the full response in its headers and body $curl_info = curl_getinfo($ch); $header_size = $curl_info["header_size"]; $header = substr($response, 0, $header_size); $body = substr($response, $header_size); $httpCode = $curl_info["http_code"]; - - return new HttpResponse($httpCode, $body, $header); + + return new HttpResponse($httpCode, $body, $header, $json_decode_assoc); } - + private static function getArrayFromQuerystring($querystring) { $pairs = explode("&", $querystring); @@ -241,7 +241,7 @@ class Unirest } return $vars; } - + /** * Ensure that a URL is encoded and safe to use with cURL * @param string $url URL to encode @@ -250,36 +250,36 @@ class Unirest private static function encodeUrl($url) { $url_parsed = parse_url($url); - + $scheme = $url_parsed['scheme'] . '://'; $host = $url_parsed['host']; $port = (isset($url_parsed['port']) ? $url_parsed['port'] : null); $path = (isset($url_parsed['path']) ? $url_parsed['path'] : null); $query = (isset($url_parsed['query']) ? $url_parsed['query'] : null); - + if ($query != null) { $query = '?' . http_build_query(Unirest::getArrayFromQuerystring($url_parsed['query'])); } - + if ($port && $port[0] != ":") $port = ":" . $port; - + $result = $scheme . $host . $port . $path . $query; return $result; } - + private static function getHeader($key, $val) { $key = trim(strtolower($key)); return $key . ": " . $val; } - + } if (!function_exists('http_chunked_decode')) { /** - * Dechunk an http 'transfer-encoding: chunked' message - * @param string $chunk the encoded message + * Dechunk an http 'transfer-encoding: chunked' message + * @param string $chunk the encoded message * @return string the decoded message */ function http_chunked_decode($chunk) @@ -287,29 +287,29 @@ if (!function_exists('http_chunked_decode')) { $pos = 0; $len = strlen($chunk); $dechunk = null; - + while (($pos < $len) && ($chunkLenHex = substr($chunk, $pos, ($newlineAt = strpos($chunk, "\n", $pos + 1)) - $pos))) { - + if (!is_hex($chunkLenHex)) { trigger_error('Value is not properly chunk encoded', E_USER_WARNING); return $chunk; } - + $pos = $newlineAt + 1; $chunkLen = hexdec(rtrim($chunkLenHex, "\r\n")); $dechunk .= substr($chunk, $pos, $chunkLen); $pos = strpos($chunk, "\n", $pos + $chunkLen) + 1; } - + return $dechunk; } } /** - * determine if a string can represent a number in hexadecimal + * determine if a string can represent a number in hexadecimal * @link http://uk1.php.net/ctype_xdigit - * @param string $hex - * @return boolean true if the string is a hex, otherwise false + * @param string $hex + * @return boolean true if the string is a hex, otherwise false */ function is_hex($hex) { From 2d4f23af38795b70e17ca8863ec50c9e665cd17b Mon Sep 17 00:00:00 2001 From: Ahmad Nassri Date: Wed, 17 Dec 2014 20:47:57 -0500 Subject: [PATCH 03/41] various cleanups - added Scrutinizer - added EditorConfig - removed closing php tags - proper usage of require_once - cleaned extra spacing --- .editorconfig | 16 ++++++++++ .scrutinizer.yml | 13 ++++++++ lib/Unirest.php | 8 ++--- lib/Unirest/HttpMethod.php | 14 ++++----- lib/Unirest/HttpResponse.php | 5 +-- lib/Unirest/Unirest.php | 59 ++++++++++++++++-------------------- 6 files changed, 67 insertions(+), 48 deletions(-) create mode 100644 .editorconfig create mode 100644 .scrutinizer.yml diff --git a/.editorconfig b/.editorconfig new file mode 100644 index 0000000..09459e5 --- /dev/null +++ b/.editorconfig @@ -0,0 +1,16 @@ +# http://editorconfig.org +root = true + +[*] +indent_style = space +indent_size = 4 +end_of_line = lf +charset = utf-8 +trim_trailing_whitespace = true +insert_final_newline = true + +[*.md] +trim_trailing_whitespace = false + +[*.yml] +trim_trailing_whitespace = false diff --git a/.scrutinizer.yml b/.scrutinizer.yml new file mode 100644 index 0000000..8edf04d --- /dev/null +++ b/.scrutinizer.yml @@ -0,0 +1,13 @@ +tools: + php_sim: true + php_pdepend: true + php_analyzer: true + php_mess_detector: true + php_changetracking: true + php_code_sniffer: true + php_cs_fixer: true + sensiolabs_security_checker: true + +filter: + excluded_paths: + - 'test/*' diff --git a/lib/Unirest.php b/lib/Unirest.php index ca05faa..49a8adf 100644 --- a/lib/Unirest.php +++ b/lib/Unirest.php @@ -1,7 +1,5 @@ \ No newline at end of file +require_once dirname(__FILE__) . '/Unirest/HttpMethod.php'; +require_once dirname(__FILE__) . '/Unirest/HttpResponse.php'; +require_once dirname(__FILE__) . '/Unirest/Unirest.php'; diff --git a/lib/Unirest/HttpMethod.php b/lib/Unirest/HttpMethod.php index 9252405..57d03b8 100644 --- a/lib/Unirest/HttpMethod.php +++ b/lib/Unirest/HttpMethod.php @@ -4,11 +4,9 @@ namespace Unirest; interface HttpMethod { - - const DELETE = "DELETE"; - const GET = "GET"; - const POST = "POST"; - const PUT = "PUT"; - const PATCH = "PATCH"; - -} \ No newline at end of file + const DELETE = 'DELETE'; + const GET = 'GET'; + const PATCH = 'PATCH'; + const POST = 'POST'; + const PUT = 'PUT'; +} diff --git a/lib/Unirest/HttpResponse.php b/lib/Unirest/HttpResponse.php index 93a78e8..0346064 100644 --- a/lib/Unirest/HttpResponse.php +++ b/lib/Unirest/HttpResponse.php @@ -23,7 +23,7 @@ class HttpResponse $this->body = $raw_body; $json = json_decode($raw_body, $json_decode_assoc); - if (json_last_error() == JSON_ERROR_NONE) { + if (json_last_error() === JSON_ERROR_NONE) { $this->body = $json; } } @@ -50,6 +50,7 @@ class HttpResponse if (property_exists($this, $property)) { $this->$property = $value; } + return $this; } @@ -61,6 +62,7 @@ class HttpResponse */ private function get_headers_from_curl_response($headers) { + $result = array(); $headers = explode("\r\n", $headers); array_shift($headers); @@ -73,5 +75,4 @@ class HttpResponse return $result; } - } diff --git a/lib/Unirest/Unirest.php b/lib/Unirest/Unirest.php index ff96d7f..b2f44b8 100644 --- a/lib/Unirest/Unirest.php +++ b/lib/Unirest/Unirest.php @@ -5,7 +5,6 @@ use Unirest\HttpResponse; class Unirest { - private static $verifyPeer = true; private static $socketTimeout = null; private static $defaultHeaders = array(); @@ -16,7 +15,7 @@ class Unirest */ public static function verifyPeer($enabled) { - Unirest::$verifyPeer = $enabled; + self::$verifyPeer = $enabled; } /** @@ -25,7 +24,7 @@ class Unirest */ public static function timeout($seconds) { - Unirest::$socketTimeout = $seconds; + self::$socketTimeout = $seconds; } /** @@ -35,7 +34,7 @@ class Unirest */ public static function defaultHeader($name, $value) { - Unirest::$defaultHeaders[$name] = $value; + self::$defaultHeaders[$name] = $value; } /** @@ -43,7 +42,7 @@ class Unirest */ public static function clearDefaultHeaders() { - Unirest::$defaultHeaders = array(); + self::$defaultHeaders = array(); } /** @@ -57,7 +56,7 @@ class Unirest */ public static function get($url, $headers = array(), $parameters = NULL, $username = NULL, $password = NULL) { - return Unirest::request(HttpMethod::GET, $url, $parameters, $headers, $username, $password); + return self::request(HttpMethod::GET, $url, $parameters, $headers, $username, $password); } /** @@ -71,7 +70,7 @@ class Unirest */ public static function post($url, $headers = array(), $body = NULL, $username = NULL, $password = NULL) { - return Unirest::request(HttpMethod::POST, $url, $body, $headers, $username, $password); + return self::request(HttpMethod::POST, $url, $body, $headers, $username, $password); } /** @@ -85,7 +84,7 @@ class Unirest */ public static function delete($url, $headers = array(), $body = NULL, $username = NULL, $password = NULL) { - return Unirest::request(HttpMethod::DELETE, $url, $body, $headers, $username, $password); + return self::request(HttpMethod::DELETE, $url, $body, $headers, $username, $password); } /** @@ -99,7 +98,7 @@ class Unirest */ public static function put($url, $headers = array(), $body = NULL, $username = NULL, $password = NULL) { - return Unirest::request(HttpMethod::PUT, $url, $body, $headers, $username, $password); + return self::request(HttpMethod::PUT, $url, $body, $headers, $username, $password); } /** @@ -113,7 +112,7 @@ class Unirest */ public static function patch($url, $headers = array(), $body = NULL, $username = NULL, $password = NULL) { - return Unirest::request(HttpMethod::PATCH, $url, $body, $headers, $username, $password); + return self::request(HttpMethod::PATCH, $url, $body, $headers, $username, $password); } /** @@ -142,7 +141,7 @@ class Unirest foreach ($arrays AS $key => $value) { $k = isset($prefix) ? $prefix . '[' . $key . ']' : $key; if (!$value instanceof \CURLFile AND (is_array($value) OR is_object($value))) { - Unirest::http_build_query_for_curl($value, $new, $k); + self::http_build_query_for_curl($value, $new, $k); } else { $new[$k] = $value; } @@ -168,22 +167,26 @@ class Unirest $lowercaseHeaders = array(); $finalHeaders = array_merge($headers, Unirest::$defaultHeaders); foreach ($finalHeaders as $key => $val) { - $lowercaseHeaders[] = Unirest::getHeader($key, $val); + $lowercaseHeaders[] = self::getHeader($key, $val); } $lowerCaseFinalHeaders = array_change_key_case($finalHeaders); + if (!array_key_exists("user-agent", $lowerCaseFinalHeaders)) { $lowercaseHeaders[] = "user-agent: unirest-php/1.1"; } + if (!array_key_exists("expect", $lowerCaseFinalHeaders)) { $lowercaseHeaders[] = "expect:"; } $ch = curl_init(); + if ($httpMethod != HttpMethod::GET) { curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $httpMethod); + if (is_array($body) || $body instanceof Traversable) { - Unirest::http_build_query_for_curl($body, $postBody); + self::http_build_query_for_curl($body, $postBody); curl_setopt($ch, CURLOPT_POSTFIELDS, $postBody); } else { curl_setopt($ch, CURLOPT_POSTFIELDS, $body); @@ -194,21 +197,24 @@ class Unirest } else { $url .= "?"; } - Unirest::http_build_query_for_curl($body, $postBody); + + self::http_build_query_for_curl($body, $postBody); $url .= urldecode(http_build_query($postBody)); } - curl_setopt($ch, CURLOPT_URL, Unirest::encodeUrl($url)); + curl_setopt($ch, CURLOPT_URL, self::encodeUrl($url)); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true); curl_setopt($ch, CURLOPT_MAXREDIRS, 10); curl_setopt($ch, CURLOPT_HTTPHEADER, $lowercaseHeaders); curl_setopt($ch, CURLOPT_HEADER, true); - curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, Unirest::$verifyPeer); + curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, self::$verifyPeer); curl_setopt($ch, CURLOPT_ENCODING, ""); // If an empty string, "", is set, a header containing all supported encoding types is sent. - if (Unirest::$socketTimeout != null) { - curl_setopt($ch, CURLOPT_TIMEOUT, Unirest::$socketTimeout); + + if (self::$socketTimeout != null) { + curl_setopt($ch, CURLOPT_TIMEOUT, self::$socketTimeout); } + if (!empty($username)) { curl_setopt($ch, CURLOPT_USERPWD, $username . ":" . ((empty($password)) ? "" : $password)); } @@ -258,7 +264,7 @@ class Unirest $query = (isset($url_parsed['query']) ? $url_parsed['query'] : null); if ($query != null) { - $query = '?' . http_build_query(Unirest::getArrayFromQuerystring($url_parsed['query'])); + $query = '?' . http_build_query(self::getArrayFromQuerystring($url_parsed['query'])); } if ($port && $port[0] != ":") @@ -290,7 +296,7 @@ if (!function_exists('http_chunked_decode')) { while (($pos < $len) && ($chunkLenHex = substr($chunk, $pos, ($newlineAt = strpos($chunk, "\n", $pos + 1)) - $pos))) { - if (!is_hex($chunkLenHex)) { + if (!ctype_xdigit($chunkLenHex)) { trigger_error('Value is not properly chunk encoded', E_USER_WARNING); return $chunk; } @@ -304,16 +310,3 @@ if (!function_exists('http_chunked_decode')) { return $dechunk; } } - -/** - * determine if a string can represent a number in hexadecimal - * @link http://uk1.php.net/ctype_xdigit - * @param string $hex - * @return boolean true if the string is a hex, otherwise false - */ -function is_hex($hex) -{ - return ctype_xdigit($hex); -} - -?> From 9465a4656a0bcc6187ff4c496e565ea4c6254d6b Mon Sep 17 00:00:00 2001 From: Ahmad Nassri Date: Wed, 17 Dec 2014 20:57:23 -0500 Subject: [PATCH 04/41] specifying PSR-2 level checks --- .scrutinizer.yml | 10 ++++++++-- 1 file changed, 8 insertions(+), 2 deletions(-) diff --git a/.scrutinizer.yml b/.scrutinizer.yml index 8edf04d..f3b87fb 100644 --- a/.scrutinizer.yml +++ b/.scrutinizer.yml @@ -4,10 +4,16 @@ tools: php_analyzer: true php_mess_detector: true php_changetracking: true - php_code_sniffer: true - php_cs_fixer: true sensiolabs_security_checker: true + php_code_sniffer: + config: + standard: 'PSR2' + + php_cs_fixer: + config: + level: 'psr2' + filter: excluded_paths: - 'test/*' From 4e68b0efab72ff1f42ff5f5c0d57ba4a6d4814d4 Mon Sep 17 00:00:00 2001 From: Ahmad Nassri Date: Wed, 17 Dec 2014 21:00:47 -0500 Subject: [PATCH 05/41] PSR: CamelCaps --- lib/Unirest/HttpResponse.php | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/lib/Unirest/HttpResponse.php b/lib/Unirest/HttpResponse.php index 0346064..480ec0c 100644 --- a/lib/Unirest/HttpResponse.php +++ b/lib/Unirest/HttpResponse.php @@ -18,7 +18,7 @@ class HttpResponse public function __construct($code, $raw_body, $headers, $json_decode_assoc = false) { $this->code = $code; - $this->headers = $this->get_headers_from_curl_response($headers); + $this->headers = $this->GetHeadersFromCurlResponse($headers); $this->raw_body = $raw_body; $this->body = $raw_body; $json = json_decode($raw_body, $json_decode_assoc); @@ -60,7 +60,7 @@ class HttpResponse * @param string $headers header string from cURL response * @return array */ - private function get_headers_from_curl_response($headers) + private function GetHeadersFromCurlResponse($headers) { $result = array(); $headers = explode("\r\n", $headers); From ea3995225c08dd87b5b475710570cf0686c524b0 Mon Sep 17 00:00:00 2001 From: Ahmad Nassri Date: Wed, 17 Dec 2014 21:06:53 -0500 Subject: [PATCH 06/41] PSR: PHP keywords in proper lower case + more camelCasing --- lib/Unirest/HttpResponse.php | 4 ++-- lib/Unirest/Unirest.php | 34 ++++++++++++++++++---------------- 2 files changed, 20 insertions(+), 18 deletions(-) diff --git a/lib/Unirest/HttpResponse.php b/lib/Unirest/HttpResponse.php index 480ec0c..f252bbc 100644 --- a/lib/Unirest/HttpResponse.php +++ b/lib/Unirest/HttpResponse.php @@ -18,7 +18,7 @@ class HttpResponse public function __construct($code, $raw_body, $headers, $json_decode_assoc = false) { $this->code = $code; - $this->headers = $this->GetHeadersFromCurlResponse($headers); + $this->headers = $this->getHeadersFromCurlResponse($headers); $this->raw_body = $raw_body; $this->body = $raw_body; $json = json_decode($raw_body, $json_decode_assoc); @@ -60,7 +60,7 @@ class HttpResponse * @param string $headers header string from cURL response * @return array */ - private function GetHeadersFromCurlResponse($headers) + private function getHeadersFromCurlResponse($headers) { $result = array(); $headers = explode("\r\n", $headers); diff --git a/lib/Unirest/Unirest.php b/lib/Unirest/Unirest.php index b2f44b8..715281e 100644 --- a/lib/Unirest/Unirest.php +++ b/lib/Unirest/Unirest.php @@ -54,7 +54,7 @@ class Unirest * @param string $password Basic Authentication password * @return string|stdObj response string or stdObj if response is json-decodable */ - public static function get($url, $headers = array(), $parameters = NULL, $username = NULL, $password = NULL) + public static function get($url, $headers = array(), $parameters = null, $username = null, $password = null) { return self::request(HttpMethod::GET, $url, $parameters, $headers, $username, $password); } @@ -68,7 +68,7 @@ class Unirest * @param string $password Basic Authentication password * @return string|stdObj response string or stdObj if response is json-decodable */ - public static function post($url, $headers = array(), $body = NULL, $username = NULL, $password = NULL) + public static function post($url, $headers = array(), $body = null, $username = null, $password = null) { return self::request(HttpMethod::POST, $url, $body, $headers, $username, $password); } @@ -82,7 +82,7 @@ class Unirest * @param string $password Basic Authentication password * @return string|stdObj response string or stdObj if response is json-decodable */ - public static function delete($url, $headers = array(), $body = NULL, $username = NULL, $password = NULL) + public static function delete($url, $headers = array(), $body = null, $username = null, $password = null) { return self::request(HttpMethod::DELETE, $url, $body, $headers, $username, $password); } @@ -96,7 +96,7 @@ class Unirest * @param string $password Basic Authentication password * @return string|stdObj response string or stdObj if response is json-decodable */ - public static function put($url, $headers = array(), $body = NULL, $username = NULL, $password = NULL) + public static function put($url, $headers = array(), $body = null, $username = null, $password = null) { return self::request(HttpMethod::PUT, $url, $body, $headers, $username, $password); } @@ -110,7 +110,7 @@ class Unirest * @param string $password Basic Authentication password * @return string|stdObj response string or stdObj if response is json-decodable */ - public static function patch($url, $headers = array(), $body = NULL, $username = NULL, $password = NULL) + public static function patch($url, $headers = array(), $body = null, $username = null, $password = null) { return self::request(HttpMethod::PATCH, $url, $body, $headers, $username, $password); } @@ -132,16 +132,16 @@ class Unirest * This function is useful for serializing multidimensional arrays, and avoid getting * the "Array to string conversion" notice */ - public static function http_build_query_for_curl($arrays, &$new = array(), $prefix = null) + public static function buildHTTPCurlQuery($arrays, &$new = array(), $prefix = null) { if (is_object($arrays)) { $arrays = get_object_vars($arrays); } - foreach ($arrays AS $key => $value) { + foreach ($arrays as $key => $value) { $k = isset($prefix) ? $prefix . '[' . $key . ']' : $key; - if (!$value instanceof \CURLFile AND (is_array($value) OR is_object($value))) { - self::http_build_query_for_curl($value, $new, $k); + if (!$value instanceof \CURLFile and (is_array($value) or is_object($value))) { + self::buildHTTPCurlQuery($value, $new, $k); } else { $new[$k] = $value; } @@ -159,10 +159,11 @@ class Unirest * @throws Exception if a cURL error occurs * @return HttpResponse */ - private static function request($httpMethod, $url, $body = NULL, $headers = array(), $username = NULL, $password = NULL, $json_decode_assoc = false) + private static function request($httpMethod, $url, $body = null, $headers = array(), $username = null, $password = null, $json_decode_assoc = false) { - if ($headers == NULL) + if ($headers == null) { $headers = array(); + } $lowercaseHeaders = array(); $finalHeaders = array_merge($headers, Unirest::$defaultHeaders); @@ -186,19 +187,19 @@ class Unirest curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $httpMethod); if (is_array($body) || $body instanceof Traversable) { - self::http_build_query_for_curl($body, $postBody); + self::buildHTTPCurlQuery($body, $postBody); curl_setopt($ch, CURLOPT_POSTFIELDS, $postBody); } else { curl_setopt($ch, CURLOPT_POSTFIELDS, $body); } - } else if (is_array($body)) { + } elseif (is_array($body)) { if (strpos($url, '?') !== false) { $url .= "&"; } else { $url .= "?"; } - self::http_build_query_for_curl($body, $postBody); + self::buildHTTPCurlQuery($body, $postBody); $url .= urldecode(http_build_query($postBody)); } @@ -221,6 +222,7 @@ class Unirest $response = curl_exec($ch); $error = curl_error($ch); + if ($error) { throw new Exception($error); } @@ -267,8 +269,9 @@ class Unirest $query = '?' . http_build_query(self::getArrayFromQuerystring($url_parsed['query'])); } - if ($port && $port[0] != ":") + if ($port && $port[0] != ":") { $port = ":" . $port; + } $result = $scheme . $host . $port . $path . $query; return $result; @@ -279,7 +282,6 @@ class Unirest $key = trim(strtolower($key)); return $key . ": " . $val; } - } if (!function_exists('http_chunked_decode')) { From 61eb281692d8dd234edefd448498e411372abbb0 Mon Sep 17 00:00:00 2001 From: Ahmad Nassri Date: Wed, 17 Dec 2014 22:29:03 -0500 Subject: [PATCH 07/41] massive cleanups - renamed classes - updated to phpunit - more PSR compliance --- .scrutinizer.yml | 4 - .travis.yml | 7 +- composer.json | 7 +- lib/Unirest.php | 6 +- lib/Unirest/{HttpMethod.php => Method.php} | 2 +- lib/Unirest/{Unirest.php => Request.php} | 99 ++-- .../{HttpResponse.php => Response.php} | 6 +- phpunit.xml | 12 + test/.gitignore | 1 - test/Unirest.php | 27 - test/Unirest/UnirestTest.php | 520 +++++++++--------- .../test_upload.txt => fixtures/upload.txt} | 0 12 files changed, 326 insertions(+), 365 deletions(-) rename lib/Unirest/{HttpMethod.php => Method.php} (88%) rename lib/Unirest/{Unirest.php => Request.php} (72%) rename lib/Unirest/{HttpResponse.php => Response.php} (91%) create mode 100644 phpunit.xml delete mode 100644 test/.gitignore delete mode 100644 test/Unirest.php rename test/{Unirest/test_upload.txt => fixtures/upload.txt} (100%) diff --git a/.scrutinizer.yml b/.scrutinizer.yml index f3b87fb..3e6cc9d 100644 --- a/.scrutinizer.yml +++ b/.scrutinizer.yml @@ -13,7 +13,3 @@ tools: php_cs_fixer: config: level: 'psr2' - -filter: - excluded_paths: - - 'test/*' diff --git a/.travis.yml b/.travis.yml index 98d9b2b..5bd57ec 100644 --- a/.travis.yml +++ b/.travis.yml @@ -4,8 +4,5 @@ php: - 5.3 - 5.4 - 5.5 - -before_script: - - sh -c "if [ '$TRAVIS_PHP_VERSION' = '5.2' ]; then wget http://iweb.dl.sourceforge.net/project/simpletest/simpletest/simpletest_1.1/simpletest_1.1.0.tar.gz; tar xf simpletest_1.1.0.tar.gz -C test; else composer install --dev --prefer-source; fi" - -script: php test/Unirest.php + - 5.6 + - hhvm diff --git a/composer.json b/composer.json index 9cc280c..7657c65 100644 --- a/composer.json +++ b/composer.json @@ -15,10 +15,11 @@ "require" : { "php" : ">=5.3.0", "ext-curl" : "*", - "ext-json" : "*" + "ext-json" : "*", + "ext-http" : "*" }, "require-dev": { - "vierbergenlars/simpletest": "*" + "phpunit/phpunit": "*" }, "autoload" : { "psr-0" : { @@ -28,4 +29,4 @@ "support" : { "email" : "support@mashape.com" } -} \ No newline at end of file +} diff --git a/lib/Unirest.php b/lib/Unirest.php index 49a8adf..a2d0a5a 100644 --- a/lib/Unirest.php +++ b/lib/Unirest.php @@ -1,5 +1,5 @@ $val) { $lowercaseHeaders[] = self::getHeader($key, $val); } $lowerCaseFinalHeaders = array_change_key_case($finalHeaders); - if (!array_key_exists("user-agent", $lowerCaseFinalHeaders)) { - $lowercaseHeaders[] = "user-agent: unirest-php/1.1"; + if (!array_key_exists('user-agent', $lowerCaseFinalHeaders)) { + $lowercaseHeaders[] = 'user-agent: unirest-php/2.0'; } - if (!array_key_exists("expect", $lowerCaseFinalHeaders)) { - $lowercaseHeaders[] = "expect:"; + if (!array_key_exists('expect', $lowerCaseFinalHeaders)) { + $lowercaseHeaders[] = 'expect:'; } $ch = curl_init(); - if ($httpMethod != HttpMethod::GET) { - curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $httpMethod); + if ($method != Method::GET) { + curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $method); if (is_array($body) || $body instanceof Traversable) { self::buildHTTPCurlQuery($body, $postBody); @@ -194,9 +196,9 @@ class Unirest } } elseif (is_array($body)) { if (strpos($url, '?') !== false) { - $url .= "&"; + $url .= '&'; } else { - $url .= "?"; + $url .= '?'; } self::buildHTTPCurlQuery($body, $postBody); @@ -210,39 +212,39 @@ class Unirest curl_setopt($ch, CURLOPT_HTTPHEADER, $lowercaseHeaders); curl_setopt($ch, CURLOPT_HEADER, true); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, self::$verifyPeer); - curl_setopt($ch, CURLOPT_ENCODING, ""); // If an empty string, "", is set, a header containing all supported encoding types is sent. + curl_setopt($ch, CURLOPT_ENCODING, ''); // If an empty string, '', is set, a header containing all supported encoding types is sent. if (self::$socketTimeout != null) { curl_setopt($ch, CURLOPT_TIMEOUT, self::$socketTimeout); } if (!empty($username)) { - curl_setopt($ch, CURLOPT_USERPWD, $username . ":" . ((empty($password)) ? "" : $password)); + curl_setopt($ch, CURLOPT_USERPWD, $username . ':' . ((empty($password)) ? '' : $password)); } $response = curl_exec($ch); $error = curl_error($ch); if ($error) { - throw new Exception($error); + throw new \Exception($error); } // Split the full response in its headers and body $curl_info = curl_getinfo($ch); - $header_size = $curl_info["header_size"]; + $header_size = $curl_info['header_size']; $header = substr($response, 0, $header_size); $body = substr($response, $header_size); - $httpCode = $curl_info["http_code"]; + $httpCode = $curl_info['http_code']; - return new HttpResponse($httpCode, $body, $header, $json_decode_assoc); + return new Response($httpCode, $body, $header); } private static function getArrayFromQuerystring($querystring) { - $pairs = explode("&", $querystring); + $pairs = explode('&', $querystring); $vars = array(); foreach ($pairs as $pair) { - $nv = explode("=", $pair, 2); + $nv = explode('=', $pair, 2); $name = $nv[0]; $value = $nv[1]; $vars[$name] = $value; @@ -269,8 +271,8 @@ class Unirest $query = '?' . http_build_query(self::getArrayFromQuerystring($url_parsed['query'])); } - if ($port && $port[0] != ":") { - $port = ":" . $port; + if ($port && $port[0] != ':') { + $port = ':' . $port; } $result = $scheme . $host . $port . $path . $query; @@ -280,35 +282,6 @@ class Unirest private static function getHeader($key, $val) { $key = trim(strtolower($key)); - return $key . ": " . $val; - } -} - -if (!function_exists('http_chunked_decode')) { - /** - * Dechunk an http 'transfer-encoding: chunked' message - * @param string $chunk the encoded message - * @return string the decoded message - */ - function http_chunked_decode($chunk) - { - $pos = 0; - $len = strlen($chunk); - $dechunk = null; - - while (($pos < $len) && ($chunkLenHex = substr($chunk, $pos, ($newlineAt = strpos($chunk, "\n", $pos + 1)) - $pos))) { - - if (!ctype_xdigit($chunkLenHex)) { - trigger_error('Value is not properly chunk encoded', E_USER_WARNING); - return $chunk; - } - - $pos = $newlineAt + 1; - $chunkLen = hexdec(rtrim($chunkLenHex, "\r\n")); - $dechunk .= substr($chunk, $pos, $chunkLen); - $pos = strpos($chunk, "\n", $pos + $chunkLen) + 1; - } - - return $dechunk; + return $key . ': ' . $val; } } diff --git a/lib/Unirest/HttpResponse.php b/lib/Unirest/Response.php similarity index 91% rename from lib/Unirest/HttpResponse.php rename to lib/Unirest/Response.php index f252bbc..be6e2af 100644 --- a/lib/Unirest/HttpResponse.php +++ b/lib/Unirest/Response.php @@ -2,7 +2,7 @@ namespace Unirest; -class HttpResponse +class Response { private $code; @@ -15,13 +15,13 @@ class HttpResponse * @param string $raw_body the raw body of the cURL response * @param string $headers raw header string from cURL response */ - public function __construct($code, $raw_body, $headers, $json_decode_assoc = false) + public function __construct($code, $raw_body, $headers) { $this->code = $code; $this->headers = $this->getHeadersFromCurlResponse($headers); $this->raw_body = $raw_body; $this->body = $raw_body; - $json = json_decode($raw_body, $json_decode_assoc); + $json = json_decode($raw_body); if (json_last_error() === JSON_ERROR_NONE) { $this->body = $json; diff --git a/phpunit.xml b/phpunit.xml new file mode 100644 index 0000000..37b77f9 --- /dev/null +++ b/phpunit.xml @@ -0,0 +1,12 @@ + + + + + ./test + + + + + + + diff --git a/test/.gitignore b/test/.gitignore deleted file mode 100644 index d875a72..0000000 --- a/test/.gitignore +++ /dev/null @@ -1 +0,0 @@ -simpletest diff --git a/test/Unirest.php b/test/Unirest.php deleted file mode 100644 index 031c389..0000000 --- a/test/Unirest.php +++ /dev/null @@ -1,27 +0,0 @@ -, and either install it " . "in your PHP include_path or put it in the test/ directory.\n"; - exit(1); -} - -// Throw an exception on any error -function exception_error_handler($errno, $errstr, $errfile, $errline) -{ - throw new ErrorException($errstr, $errno, 0, $errfile, $errline); -} - -set_error_handler('exception_error_handler'); -error_reporting(E_ALL | E_STRICT); - -require_once(dirname(__FILE__) . '/../lib/Unirest.php'); - -require_once(dirname(__FILE__) . '/Unirest/UnirestTest.php'); - -?> \ No newline at end of file diff --git a/test/Unirest/UnirestTest.php b/test/Unirest/UnirestTest.php index 188fa85..688ece4 100644 --- a/test/Unirest/UnirestTest.php +++ b/test/Unirest/UnirestTest.php @@ -1,27 +1,33 @@ "application/json" + $response = Request::get('http://httpbin.org/get?name=Mark', array( + 'Accept' => 'application/json' ), array( - "nick" => "thefosk" + 'nick' => 'thefosk' )); - - $this->assertEqual(200, $response->code); - + + $this->assertEquals(200, $response->code); + $args = $response->body->args; - $this->assertEqual("Mark", $args->name); - $this->assertEqual("thefosk", $args->nick); + $this->assertEquals('Mark', $args->name); + $this->assertEquals('thefosk', $args->nick); } - + public function testGetMultidimensionalArray() { - $response = Unirest::get("http://httpbin.org/get", array( - "Accept" => "application/json" + $response = Request::get('http://httpbin.org/get', array( + 'Accept' => 'application/json' ), array( 'key' => 'value', 'items' => array( @@ -29,202 +35,204 @@ class UnirestTest extends UnitTestCase 'item2' ) )); - - $this->assertEqual(200, $response->code); - + + $this->assertEquals(200, $response->code); + $args = $response->body->args; - - $this->assertEqual("value", $args->key); - $this->assertEqual("item1", $args->{"items[0]"}); - $this->assertEqual("item2", $args->{"items[1]"}); + + $this->assertEquals('value', $args->key); + $this->assertEquals('item1', $args->{'items[0]'}); + $this->assertEquals('item2', $args->{'items[1]'}); } - + public function testGetWithDots() { - $response = Unirest::get("http://httpbin.org/get", array( - "Accept" => "application/json" + $response = Request::get('http://httpbin.org/get', array( + 'Accept' => 'application/json' ), array( - "user.name" => "Mark", - "nick" => "thefosk" + 'user.name' => 'Mark', + 'nick' => 'thefosk' )); - - $this->assertEqual(200, $response->code); - + + $this->assertEquals(200, $response->code); + $args = $response->body->args; - $this->assertEqual("Mark", $args->{"user.name"}); - $this->assertEqual("thefosk", $args->nick); + $this->assertEquals('Mark', $args->{'user.name'}); + $this->assertEquals('thefosk', $args->nick); } - + public function testGetWithDots2() { - $response = Unirest::get("http://httpbin.org/get", array( - "Accept" => "application/json" + $response = Request::get('http://httpbin.org/get', array( + 'Accept' => 'application/json' ), array( - "user.name" => "Mark Bond", - "nick" => "thefosk" + 'user.name' => 'Mark Bond', + 'nick' => 'thefosk' )); - - $this->assertEqual(200, $response->code); - + + $this->assertEquals(200, $response->code); + $args = $response->body->args; - $this->assertEqual("Mark Bond", $args->{"user.name"}); - $this->assertEqual("thefosk", $args->nick); + $this->assertEquals('Mark Bond', $args->{'user.name'}); + $this->assertEquals('thefosk', $args->nick); } - + public function testPost() { - $response = Unirest::post("http://httpbin.org/post", array( - "Accept" => "application/json" + $response = Request::post('http://httpbin.org/post', array( + 'Accept' => 'application/json' ), array( - "name" => "Mark", - "nick" => "thefosk" + 'name' => 'Mark', + 'nick' => 'thefosk' )); - - $this->assertEqual(200, $response->code); - + + $this->assertEquals(200, $response->code); + $form = $response->body->form; - $this->assertEqual("Mark", $form->name); - $this->assertEqual("thefosk", $form->nick); + $this->assertEquals('Mark', $form->name); + $this->assertEquals('thefosk', $form->nick); } public function testPostWithEqualSign() { - $response = Unirest::post("http://httpbin.org/post", array( - "Accept" => "application/json" + $response = Request::post('http://httpbin.org/post', array( + 'Accept' => 'application/json' ), array( - "name" => "Mark=Hello" + 'name' => 'Mark=Hello' )); - - $this->assertEqual(200, $response->code); - + + $this->assertEquals(200, $response->code); + $form = $response->body->form; - $this->assertEqual("Mark=Hello", $form->name); + $this->assertEquals('Mark=Hello', $form->name); } public function testGetWithEqualSign() { - $response = Unirest::get("http://httpbin.org/get", array( - "Accept" => "application/json" + $response = Request::get('http://httpbin.org/get', array( + 'Accept' => 'application/json' ), array( - "name" => "Mark=Hello" + 'name' => 'Mark=Hello' )); - - $this->assertEqual(200, $response->code); - - $args = $response->body->args; - $this->assertEqual("Mark=Hello", $args->name); - $response = Unirest::get("http://httpbin.org/get", array( - "Accept" => "application/json" - ), array( - "name" => "Mark=Hello=John" - )); - - $this->assertEqual(200, $response->code); - + $this->assertEquals(200, $response->code); + $args = $response->body->args; - $this->assertEqual("Mark=Hello=John", $args->name); + $this->assertEquals('Mark=Hello', $args->name); + + $response = Request::get('http://httpbin.org/get', array( + 'Accept' => 'application/json' + ), array( + 'name' => 'Mark=Hello=John' + )); + + $this->assertEquals(200, $response->code); + + $args = $response->body->args; + $this->assertEquals('Mark=Hello=John', $args->name); } public function testPostArray() { - $response = Unirest::post("http://httpbin.org/post", array( - "Accept" => "application/json" + $response = Request::post('http://httpbin.org/post', array( + 'Accept' => 'application/json' ), array( - "name[0]" => "Mark", - "name[1]" => "John" + 'name[0]' => 'Mark', + 'name[1]' => 'John' )); - - $this->assertEqual(200, $response->code); - + + $this->assertEquals(200, $response->code); + $form = $response->body->form; - $this->assertEqual("Mark", $form->{"name[0]"}); - $this->assertEqual("John", $form->{"name[1]"}); + $this->assertEquals('Mark', $form->{'name[0]'}); + $this->assertEquals('John', $form->{'name[1]'}); } public function testGetArray() { - $response = Unirest::get("http://httpbin.org/get", array(), array( - "name[0]" => "Mark", - "name[1]" => "John" + $response = Request::get('http://httpbin.org/get', array(), array( + 'name[0]' => 'Mark', + 'name[1]' => 'John' )); - - $this->assertEqual(200, $response->code); - + + $this->assertEquals(200, $response->code); + $args = $response->body->args; - $this->assertEqual("Mark", $args->{"name[0]"}); - $this->assertEqual("John", $args->{"name[1]"}); + $this->assertEquals('Mark', $args->{'name[0]'}); + $this->assertEquals('John', $args->{'name[1]'}); } - + public function testPostWithDots() { - $response = Unirest::post("http://httpbin.org/post", array( - "Accept" => "application/json" + $response = Request::post('http://httpbin.org/post', array( + 'Accept' => 'application/json' ), array( - "user.name" => "Mark", - "nick" => "thefosk" + 'user.name' => 'Mark', + 'nick' => 'thefosk' )); - - $this->assertEqual(200, $response->code); - + + $this->assertEquals(200, $response->code); + $form = $response->body->form; - $this->assertEqual("Mark", $form->{"user.name"}); - $this->assertEqual("thefosk", $form->nick); + $this->assertEquals('Mark', $form->{'user.name'}); + $this->assertEquals('thefosk', $form->nick); } - + public function testRawPost() { - $response = Unirest::post("http://httpbin.org/post", array( - "Accept" => "application/json" + $response = Request::post('http://httpbin.org/post', array( + 'Accept' => 'application/json', + 'Content-Type' => 'application/json' ), json_encode(array( - "author" => "Sam Sullivan" + 'author' => 'Sam Sullivan' ))); - - $this->assertEqual(200, $response->code); - + + $this->assertEquals(200, $response->code); + $json = $response->body->json; - $this->assertEqual("Sam Sullivan", $json->author); + + $this->assertEquals('Sam Sullivan', $json->author); } - + public function testUpload() - { - $response = Unirest::post("http://httpbin.org/post", array( - "Accept" => "application/json" + { + $response = Request::post('http://httpbin.org/post', array( + 'Accept' => 'application/json' ), array( - "name" => "Mark", - "file" => Unirest::file(dirname(__FILE__) . "/test_upload.txt") + 'name' => 'Mark', + 'file' => Request::file(UPLOAD_FIXTURE) )); - $this->assertEqual(200, $response->code); - + $this->assertEquals(200, $response->code); + $files = $response->body->files; - $this->assertEqual("This is a test", $files->file); - + $this->assertEquals('This is a test', $files->file); + $form = $response->body->form; - $this->assertEqual("Mark", $form->name); + $this->assertEquals('Mark', $form->name); } public function testUploadIfFilePartOfData() - { - $response = Unirest::post("http://httpbin.org/post", array( - "Accept" => "application/json" + { + $response = Request::post('http://httpbin.org/post', array( + 'Accept' => 'application/json' ), array( - "name" => "Mark", - "files[owl.gif]" => Unirest::file(dirname(__FILE__) . "/test_upload.txt") + 'name' => 'Mark', + 'files[owl.gif]' => Request::file(UPLOAD_FIXTURE) )); - $this->assertEqual(200, $response->code); - + $this->assertEquals(200, $response->code); + //$files = $response->body->files; - //$this->assertEqual("This is a test", $files->file); - + //$this->assertEquals('This is a test', $files->file); + $form = $response->body->form; - $this->assertEqual("Mark", $form->name); + $this->assertEquals('Mark', $form->name); } - + public function testPostMultidimensionalArray() { - $response = Unirest::post("http://httpbin.org/post", array( - "Accept" => "application/json" + $response = Request::post('http://httpbin.org/post', array( + 'Accept' => 'application/json' ), array( 'key' => 'value', 'items' => array( @@ -232,143 +240,145 @@ class UnirestTest extends UnitTestCase 'item2' ) )); - - $this->assertEqual(200, $response->code); - + + $this->assertEquals(200, $response->code); + $form = $response->body->form; - $this->assertEqual("value", $form->key); - $this->assertEqual("item1", $form->{"items[0]"}); - $this->assertEqual("item2", $form->{"items[1]"}); - } - - public function testPut() - { - $response = Unirest::put("http://httpbin.org/put", array( - "Accept" => "application/json" - ), array( - "name" => "Mark", - "nick" => "thefosk" - )); - - $this->assertEqual(200, $response->code); - - $form = $response->body->form; - $this->assertEqual("Mark", $form->name); - $this->assertEqual("thefosk", $form->nick); - } - - public function testPatch() - { - $response = Unirest::patch("http://httpbin.org/patch", array( - "Accept" => "application/json" - ), array( - "name" => "Mark", - "nick" => "thefosk" - )); - - $this->assertEqual(200, $response->code); - - $form = $response->body->form; - $this->assertEqual("Mark", $form->name); - $this->assertEqual("thefosk", $form->nick); - } - - public function testDelete() - { - $response = Unirest::delete("http://httpbin.org/delete", array( - "Accept" => "application/json", - "Content-Type" => "application/x-www-form-urlencoded" - ), array( - "name" => "Mark", - "nick" => "thefosk" - )); - - $this->assertEqual(200, $response->code); - $data = $response->body->data; - $this->assertFalse(empty($data)); - } - - public function testTimeoutFail() - { - Unirest::timeout(1); - - $this->expectException(); - $response = Unirest::get("http://httpbin.org/delay/3"); - - Unirest::timeout(null); // Cleaning timeout for the other tests - } - - public function testTimeoutSuccess() - { - Unirest::timeout(3); - - $response = Unirest::get("http://httpbin.org/delay/1"); - $this->assertEqual(200, $response->code); - - Unirest::timeout(null); // Cleaning timeout for the other tests - } - - public function testDefaultHeader() - { - Unirest::defaultHeader("Hello", "custom"); - $response = Unirest::get("http://httpbin.org/get"); - - $this->assertEqual(200, $response->code); - $headers = $response->body->headers; - $properties = get_object_vars($headers); - $this->assertTrue(array_key_exists("Hello", $properties)); - $this->assertEqual("custom", $headers->Hello); - $response = Unirest::get("http://httpbin.org/get"); - - $this->assertEqual(200, $response->code); - $headers = $response->body->headers; - $properties = get_object_vars($headers); - $this->assertTrue(array_key_exists("Hello", $properties)); - $this->assertEqual("custom", $headers->Hello); - Unirest::clearDefaultHeaders(); - $response = Unirest::get("http://httpbin.org/get"); - - $this->assertEqual(200, $response->code); - $headers = $response->body->headers; - $properties = get_object_vars($headers); - $this->assertFalse(array_key_exists("Hello", $properties)); - } - - public function testGzip() - { - $response = Unirest::get("http://httpbin.org/gzip"); - $args = $response->body; - $this->assertEqual(true, $args->gzipped); - } - - public function testBasicAuthentication() - { - $response = Unirest::get("http://httpbin.org/get", null, null, "user", "password"); - $headers = $response->body->headers; - $this->assertEqual("Basic dXNlcjpwYXNzd29yZA==", $headers->Authorization); + $this->assertEquals('value', $form->key); + $this->assertEquals('item1', $form->{'items[0]'}); + $this->assertEquals('item2', $form->{'items[1]'}); } - public function testCustomHeaders() + public function testPut() { - $response = Unirest::get('http://httpbin.org/get', array( + $response = Request::put('http://httpbin.org/put', array( + 'Accept' => 'application/json' + ), array( + 'name' => 'Mark', + 'nick' => 'thefosk' + )); + + $this->assertEquals(200, $response->code); + + $form = $response->body->form; + $this->assertEquals('Mark', $form->name); + $this->assertEquals('thefosk', $form->nick); + } + + public function testPatch() + { + $response = Request::patch('http://httpbin.org/patch', array( + 'Accept' => 'application/json' + ), array( + 'name' => 'Mark', + 'nick' => 'thefosk' + )); + + $this->assertEquals(200, $response->code); + + $form = $response->body->form; + $this->assertEquals('Mark', $form->name); + $this->assertEquals('thefosk', $form->nick); + } + + public function testDelete() + { + $response = Request::delete('http://httpbin.org/delete', array( + 'Accept' => 'application/json', + 'Content-Type' => 'application/x-www-form-urlencoded' + ), array( + 'name' => 'Mark', + 'nick' => 'thefosk' + )); + + $this->assertEquals(200, $response->code); + $data = $response->body->data; + $this->assertTrue(empty($data)); + } + + /** + * @expectedException Exception + */ + public function testTimeoutFail() + { + Request::timeout(1); + + $response = Request::get('http://httpbin.org/delay/3'); + + Request::timeout(null); // Cleaning timeout for the other tests + } + + public function testTimeoutSuccess() + { + Request::timeout(3); + + $response = Request::get('http://httpbin.org/delay/1'); + $this->assertEquals(200, $response->code); + + Request::timeout(null); // Cleaning timeout for the other tests + } + + public function testDefaultHeader() + { + Request::defaultHeader('Hello', 'custom'); + $response = Request::get('http://httpbin.org/get'); + + $this->assertEquals(200, $response->code); + $headers = $response->body->headers; + $properties = get_object_vars($headers); + $this->assertTrue(array_key_exists('Hello', $properties)); + $this->assertEquals('custom', $headers->Hello); + $response = Request::get('http://httpbin.org/get'); + + $this->assertEquals(200, $response->code); + $headers = $response->body->headers; + $properties = get_object_vars($headers); + $this->assertTrue(array_key_exists('Hello', $properties)); + $this->assertEquals('custom', $headers->Hello); + Request::clearDefaultHeaders(); + $response = Request::get('http://httpbin.org/get'); + + $this->assertEquals(200, $response->code); + $headers = $response->body->headers; + $properties = get_object_vars($headers); + $this->assertFalse(array_key_exists('Hello', $properties)); + } + + public function testGzip() + { + $response = Request::get('http://httpbin.org/gzip'); + $args = $response->body; + $this->assertEquals(true, $args->gzipped); + } + + public function testBasicAuthentication() + { + $response = Request::get('http://httpbin.org/get', null, null, 'user', 'password'); + $headers = $response->body->headers; + $this->assertEquals('Basic dXNlcjpwYXNzd29yZA==', $headers->Authorization); + } + + public function testCustomHeaders() + { + $response = Request::get('http://httpbin.org/get', array( 'user-agent' => 'ciao', )); - $this->assertEqual(200, $response->code); + $this->assertEquals(200, $response->code); $headers = $response->body->headers; - $this->assertEqual("ciao", $headers->{'User-Agent'}); + $this->assertEquals('ciao', $headers->{'User-Agent'}); } public function testHttpBuildQueryWhenCurlFile() { - $file = Unirest::file(dirname(__FILE__) . "/test_upload.txt"); + $file = Request::file(UPLOAD_FIXTURE); $body = array( - "to" => "mail@mailinator.com", - "from" => "mail@mailinator.com", - "file" => $file + 'to' => 'mail@mailinator.com', + 'from' => 'mail@mailinator.com', + 'file' => $file ); - Unirest::http_build_query_for_curl($body, $postBody); - $this->assertEqual($postBody['file'], $file); + Request::buildHTTPCurlQuery($body, $postBody); + $this->assertEquals($postBody['file'], $file); } } diff --git a/test/Unirest/test_upload.txt b/test/fixtures/upload.txt similarity index 100% rename from test/Unirest/test_upload.txt rename to test/fixtures/upload.txt From cda471ebdb38bcf386b7d3ee2cede1d2934fc3a6 Mon Sep 17 00:00:00 2001 From: Ahmad Nassri Date: Wed, 17 Dec 2014 22:33:07 -0500 Subject: [PATCH 08/41] removing extra dependency --- composer.json | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/composer.json b/composer.json index 7657c65..3d07361 100644 --- a/composer.json +++ b/composer.json @@ -15,8 +15,7 @@ "require" : { "php" : ">=5.3.0", "ext-curl" : "*", - "ext-json" : "*", - "ext-http" : "*" + "ext-json" : "*" }, "require-dev": { "phpunit/phpunit": "*" From 6347fa33ee2253c3d3ab98b481c361e07cd156a6 Mon Sep 17 00:00:00 2001 From: Ahmad Nassri Date: Wed, 17 Dec 2014 22:38:46 -0500 Subject: [PATCH 09/41] modifying directory name to standard usage --- composer.json | 2 +- {lib => src}/Unirest.php | 0 {lib => src}/Unirest/Method.php | 0 {lib => src}/Unirest/Request.php | 0 {lib => src}/Unirest/Response.php | 0 test/Unirest/UnirestTest.php => tests/Unirest/RequestTest.php | 0 {test => tests}/fixtures/upload.txt | 0 7 files changed, 1 insertion(+), 1 deletion(-) rename {lib => src}/Unirest.php (100%) rename {lib => src}/Unirest/Method.php (100%) rename {lib => src}/Unirest/Request.php (100%) rename {lib => src}/Unirest/Response.php (100%) rename test/Unirest/UnirestTest.php => tests/Unirest/RequestTest.php (100%) rename {test => tests}/fixtures/upload.txt (100%) diff --git a/composer.json b/composer.json index 3d07361..2fbe96e 100644 --- a/composer.json +++ b/composer.json @@ -22,7 +22,7 @@ }, "autoload" : { "psr-0" : { - "Unirest" : "lib" + "Unirest" : "src" } }, "support" : { diff --git a/lib/Unirest.php b/src/Unirest.php similarity index 100% rename from lib/Unirest.php rename to src/Unirest.php diff --git a/lib/Unirest/Method.php b/src/Unirest/Method.php similarity index 100% rename from lib/Unirest/Method.php rename to src/Unirest/Method.php diff --git a/lib/Unirest/Request.php b/src/Unirest/Request.php similarity index 100% rename from lib/Unirest/Request.php rename to src/Unirest/Request.php diff --git a/lib/Unirest/Response.php b/src/Unirest/Response.php similarity index 100% rename from lib/Unirest/Response.php rename to src/Unirest/Response.php diff --git a/test/Unirest/UnirestTest.php b/tests/Unirest/RequestTest.php similarity index 100% rename from test/Unirest/UnirestTest.php rename to tests/Unirest/RequestTest.php diff --git a/test/fixtures/upload.txt b/tests/fixtures/upload.txt similarity index 100% rename from test/fixtures/upload.txt rename to tests/fixtures/upload.txt From b6efa7e1cc9c8de868d672a8bd59ad475988dc26 Mon Sep 17 00:00:00 2001 From: Ahmad Nassri Date: Wed, 17 Dec 2014 22:44:33 -0500 Subject: [PATCH 10/41] PSR compliance --- src/Unirest/Request.php | 18 +++++++++--------- 1 file changed, 9 insertions(+), 9 deletions(-) diff --git a/src/Unirest/Request.php b/src/Unirest/Request.php index 1806d60..4638820 100644 --- a/src/Unirest/Request.php +++ b/src/Unirest/Request.php @@ -1,10 +1,10 @@ Date: Wed, 17 Dec 2014 22:45:58 -0500 Subject: [PATCH 11/41] identation fix --- tests/Unirest/RequestTest.php | 21 +++++++++++---------- 1 file changed, 11 insertions(+), 10 deletions(-) diff --git a/tests/Unirest/RequestTest.php b/tests/Unirest/RequestTest.php index 688ece4..312ec16 100644 --- a/tests/Unirest/RequestTest.php +++ b/tests/Unirest/RequestTest.php @@ -1,9 +1,9 @@ 'mail@mailinator.com', - 'from' => 'mail@mailinator.com', - 'file' => $file - ); - Request::buildHTTPCurlQuery($body, $postBody); - $this->assertEquals($postBody['file'], $file); + $file = Request::file(UPLOAD_FIXTURE); + $body = array( + 'to' => 'mail@mailinator.com', + 'from' => 'mail@mailinator.com', + 'file' => $file + ); + + Request::buildHTTPCurlQuery($body, $postBody); + $this->assertEquals($postBody['file'], $file); } } From 07aa7ab19f3c8786351db829fd69120e87c1f95f Mon Sep 17 00:00:00 2001 From: Ahmad Nassri Date: Wed, 17 Dec 2014 23:03:20 -0500 Subject: [PATCH 12/41] removing redundant setter/getter + adding PECL_HTTP like header parsing --- src/Unirest/Response.php | 73 +++++++++++++++------------------------- 1 file changed, 28 insertions(+), 45 deletions(-) diff --git a/src/Unirest/Response.php b/src/Unirest/Response.php index be6e2af..ca9cd5c 100644 --- a/src/Unirest/Response.php +++ b/src/Unirest/Response.php @@ -5,10 +5,10 @@ namespace Unirest; class Response { - private $code; - private $raw_body; - private $body; - private $headers; + public $code; + public $raw_body; + public $body; + public $headers; /** * @param int $code response code of the cURL request @@ -18,7 +18,7 @@ class Response public function __construct($code, $raw_body, $headers) { $this->code = $code; - $this->headers = $this->getHeadersFromCurlResponse($headers); + $this->headers = http_parse_headers($headers); $this->raw_body = $raw_body; $this->body = $raw_body; $json = json_decode($raw_body); @@ -27,52 +27,35 @@ class Response $this->body = $json; } } +} - /** - * Return a property of the response if it exists. - * Possibilities include: code, raw_body, headers, body (if the response is json-decodable) - * @return mixed - */ - public function __get($property) - { - if (property_exists($this, $property)) { - return $this->$property; - } - } +if (!function_exists('http_parse_headers')) { + function http_parse_headers($raw_headers) { + $headers = array(); + $key = ''; - /** - * Set the properties of this object - * @param string $property the property name - * @param mixed $value the property value - */ - public function __set($property, $value) - { - if (property_exists($this, $property)) { - $this->$property = $value; - } + foreach(explode("\n", $raw_headers) as $i => $h) { + $h = explode(':', $h, 2); - return $this; - } + if (isset($h[1])) { + if (!isset($headers[$h[0]])) { + $headers[$h[0]] = trim($h[1]); + } elseif (is_array($headers[$h[0]])) { + $headers[$h[0]] = array_merge($headers[$h[0]], array(trim($h[1]))); + } else { + $headers[$h[0]] = array_merge(array($headers[$h[0]]), array(trim($h[1]))); + } - /** - * Retrieve the cURL response headers from the - * header string and convert it into an array - * @param string $headers header string from cURL response - * @return array - */ - private function getHeadersFromCurlResponse($headers) - { - $result = array(); - $headers = explode("\r\n", $headers); - array_shift($headers); - - foreach ($headers as $line) { - if (strstr($line, ': ')) { - list($key, $value) = explode(': ', $line); - $result[$key] = $value; + $key = $h[0]; + } else { + if (substr($h[0], 0, 1) == "\t") { + $headers[$key] .= "\r\n\t".trim($h[0]); + } elseif (!$key){ + $headers[0] = trim($h[0]); + } } } - return $result; + return $headers; } } From 814cee98fc9c8a07ca583b37b015d0720b4894fc Mon Sep 17 00:00:00 2001 From: Ahmad Nassri Date: Wed, 17 Dec 2014 23:56:06 -0500 Subject: [PATCH 13/41] removing php5.3 --- .travis.yml | 1 - composer.json | 2 +- 2 files changed, 1 insertion(+), 2 deletions(-) diff --git a/.travis.yml b/.travis.yml index 5bd57ec..2244fa6 100644 --- a/.travis.yml +++ b/.travis.yml @@ -1,7 +1,6 @@ language: php php: - - 5.3 - 5.4 - 5.5 - 5.6 diff --git a/composer.json b/composer.json index 2fbe96e..8324c12 100644 --- a/composer.json +++ b/composer.json @@ -13,7 +13,7 @@ } ], "require" : { - "php" : ">=5.3.0", + "php" : ">=5.4.0", "ext-curl" : "*", "ext-json" : "*" }, From dd9edca0445374b3324d494b88e76b0b8ad7f09b Mon Sep 17 00:00:00 2001 From: Ahmad Nassri Date: Wed, 17 Dec 2014 23:56:17 -0500 Subject: [PATCH 14/41] fixing phpunit test directory --- phpunit.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/phpunit.xml b/phpunit.xml index 37b77f9..476064e 100644 --- a/phpunit.xml +++ b/phpunit.xml @@ -2,7 +2,7 @@ - ./test + ./tests From 8ee4ba0753c11d096bde38c79aeebe7d965473bf Mon Sep 17 00:00:00 2001 From: Ahmad Nassri Date: Wed, 17 Dec 2014 23:57:06 -0500 Subject: [PATCH 15/41] adding a better query string parser that can handle arrays --- src/Unirest/Request.php | 22 ++++++++++------------ src/Unirest/Response.php | 6 ++++++ 2 files changed, 16 insertions(+), 12 deletions(-) diff --git a/src/Unirest/Request.php b/src/Unirest/Request.php index 4638820..aca5953 100644 --- a/src/Unirest/Request.php +++ b/src/Unirest/Request.php @@ -188,7 +188,7 @@ class Request if ($method != Method::GET) { curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $method); - if (is_array($body) || $body instanceof Traversable) { + if (is_array($body) || $body instanceof \Traversable) { self::buildHTTPCurlQuery($body, $postBody); curl_setopt($ch, CURLOPT_POSTFIELDS, $postBody); } else { @@ -239,17 +239,15 @@ class Request return new Response($httpCode, $body, $header); } - private static function getArrayFromQuerystring($querystring) + private static function getArrayFromQuerystring($query) { - $pairs = explode('&', $querystring); - $vars = array(); - foreach ($pairs as $pair) { - $nv = explode('=', $pair, 2); - $name = $nv[0]; - $value = $nv[1]; - $vars[$name] = $value; - } - return $vars; + $query = preg_replace_callback('/(?:^|(?<=&))[^=[]+/', function($match) { + return bin2hex(urldecode($match[0])); + }, $query); + + parse_str($query, $values); + + return array_combine(array_map('hex2bin', array_keys($values)), $values); } /** @@ -268,7 +266,7 @@ class Request $query = (isset($url_parsed['query']) ? $url_parsed['query'] : null); if ($query != null) { - $query = '?' . http_build_query(self::getArrayFromQuerystring($url_parsed['query'])); + $query = '?' . http_build_query(self::getArrayFromQuerystring($query)); } if ($port && $port[0] != ':') { diff --git a/src/Unirest/Response.php b/src/Unirest/Response.php index ca9cd5c..66aad29 100644 --- a/src/Unirest/Response.php +++ b/src/Unirest/Response.php @@ -29,6 +29,12 @@ class Response } } +/** + * if PECL_HTTP is not available use a fall back function + * + * thanks to ricardovermeltfoort@gmail.com + * http://php.net/manual/en/function.http-parse-headers.php#112986 + */ if (!function_exists('http_parse_headers')) { function http_parse_headers($raw_headers) { $headers = array(); From ed76b178848a81422b7c68ff3fc6b1dd463f9f06 Mon Sep 17 00:00:00 2001 From: Ahmad Nassri Date: Wed, 17 Dec 2014 23:57:27 -0500 Subject: [PATCH 16/41] test fixes --- tests/Unirest/RequestTest.php | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/tests/Unirest/RequestTest.php b/tests/Unirest/RequestTest.php index 312ec16..d24fd57 100644 --- a/tests/Unirest/RequestTest.php +++ b/tests/Unirest/RequestTest.php @@ -1,11 +1,11 @@ Date: Thu, 18 Dec 2014 00:05:49 -0500 Subject: [PATCH 17/41] fixes from scrutinizer-ci --- src/Unirest/Request.php | 2 +- src/Unirest/Response.php | 63 ++++++++++++++++++----------------- tests/Unirest/RequestTest.php | 4 +-- 3 files changed, 36 insertions(+), 33 deletions(-) diff --git a/src/Unirest/Request.php b/src/Unirest/Request.php index aca5953..5c8276b 100644 --- a/src/Unirest/Request.php +++ b/src/Unirest/Request.php @@ -241,7 +241,7 @@ class Request private static function getArrayFromQuerystring($query) { - $query = preg_replace_callback('/(?:^|(?<=&))[^=[]+/', function($match) { + $query = preg_replace_callback('/(?:^|(?<=&))[^=[]+/', function ($match) { return bin2hex(urldecode($match[0])); }, $query); diff --git a/src/Unirest/Response.php b/src/Unirest/Response.php index 66aad29..b99cf89 100644 --- a/src/Unirest/Response.php +++ b/src/Unirest/Response.php @@ -18,7 +18,7 @@ class Response public function __construct($code, $raw_body, $headers) { $this->code = $code; - $this->headers = http_parse_headers($headers); + $this->headers = $this->parseHeaders($headers); $this->raw_body = $raw_body; $this->body = $raw_body; $json = json_decode($raw_body); @@ -27,41 +27,44 @@ class Response $this->body = $json; } } -} -/** - * if PECL_HTTP is not available use a fall back function - * - * thanks to ricardovermeltfoort@gmail.com - * http://php.net/manual/en/function.http-parse-headers.php#112986 - */ -if (!function_exists('http_parse_headers')) { - function http_parse_headers($raw_headers) { - $headers = array(); - $key = ''; + /** + * if PECL_HTTP is not available use a fall back function + * + * thanks to ricardovermeltfoort@gmail.com + * http://php.net/manual/en/function.http-parse-headers.php#112986 + */ + private function parseHeaders($raw_headers) { + if (function_exists('http_parse_headers')) { + return http_parse_headers($raw_headers); + } else { - foreach(explode("\n", $raw_headers) as $i => $h) { - $h = explode(':', $h, 2); + $headers = array(); + $key = ''; - if (isset($h[1])) { - if (!isset($headers[$h[0]])) { - $headers[$h[0]] = trim($h[1]); - } elseif (is_array($headers[$h[0]])) { - $headers[$h[0]] = array_merge($headers[$h[0]], array(trim($h[1]))); + foreach (explode("\n", $raw_headers) as $i => $h) { + $h = explode(':', $h, 2); + + if (isset($h[1])) { + if (!isset($headers[$h[0]])) { + $headers[$h[0]] = trim($h[1]); + } elseif (is_array($headers[$h[0]])) { + $headers[$h[0]] = array_merge($headers[$h[0]], array(trim($h[1]))); + } else { + $headers[$h[0]] = array_merge(array($headers[$h[0]]), array(trim($h[1]))); + } + + $key = $h[0]; } else { - $headers[$h[0]] = array_merge(array($headers[$h[0]]), array(trim($h[1]))); - } - - $key = $h[0]; - } else { - if (substr($h[0], 0, 1) == "\t") { - $headers[$key] .= "\r\n\t".trim($h[0]); - } elseif (!$key){ - $headers[0] = trim($h[0]); + if (substr($h[0], 0, 1) == "\t") { + $headers[$key] .= "\r\n\t".trim($h[0]); + } elseif (!$key) { + $headers[0] = trim($h[0]); + } } } - } - return $headers; + return $headers; + } } } diff --git a/tests/Unirest/RequestTest.php b/tests/Unirest/RequestTest.php index d24fd57..9c52f26 100644 --- a/tests/Unirest/RequestTest.php +++ b/tests/Unirest/RequestTest.php @@ -303,7 +303,7 @@ class UnirestTest extends \PHPUnit_Framework_TestCase { Request::timeout(1); - $response = Request::get('http://httpbin.org/delay/3'); + Request::get('http://httpbin.org/delay/3'); Request::timeout(null); // Cleaning timeout for the other tests } @@ -353,7 +353,7 @@ class UnirestTest extends \PHPUnit_Framework_TestCase public function testBasicAuthentication() { - $response = Request::get('http://httpbin.org/get', null, null, 'user', 'password'); + $response = Request::get('http://httpbin.org/get', null, array(), 'user', 'password'); $headers = $response->body->headers; $this->assertEquals('Basic dXNlcjpwYXNzd29yZA==', $headers->Authorization); } From d00412984204c5d1cba669af293c0ca726a689ba Mon Sep 17 00:00:00 2001 From: Ahmad Nassri Date: Thu, 18 Dec 2014 00:08:12 -0500 Subject: [PATCH 18/41] more scrutinizer-ci --- src/Unirest/Response.php | 3 ++- tests/Unirest/RequestTest.php | 2 +- 2 files changed, 3 insertions(+), 2 deletions(-) diff --git a/src/Unirest/Response.php b/src/Unirest/Response.php index b99cf89..c77477c 100644 --- a/src/Unirest/Response.php +++ b/src/Unirest/Response.php @@ -34,7 +34,8 @@ class Response * thanks to ricardovermeltfoort@gmail.com * http://php.net/manual/en/function.http-parse-headers.php#112986 */ - private function parseHeaders($raw_headers) { + private function parseHeaders($raw_headers) + { if (function_exists('http_parse_headers')) { return http_parse_headers($raw_headers); } else { diff --git a/tests/Unirest/RequestTest.php b/tests/Unirest/RequestTest.php index 9c52f26..bb68c4a 100644 --- a/tests/Unirest/RequestTest.php +++ b/tests/Unirest/RequestTest.php @@ -353,7 +353,7 @@ class UnirestTest extends \PHPUnit_Framework_TestCase public function testBasicAuthentication() { - $response = Request::get('http://httpbin.org/get', null, array(), 'user', 'password'); + $response = Request::get('http://httpbin.org/get', array(), array(), 'user', 'password'); $headers = $response->body->headers; $this->assertEquals('Basic dXNlcjpwYXNzd29yZA==', $headers->Authorization); } From eccbc76469cb213cbe0aa6af62388568ee811c0c Mon Sep 17 00:00:00 2001 From: Ahmad Nassri Date: Thu, 18 Dec 2014 01:16:40 -0500 Subject: [PATCH 19/41] improving curl post body flattening for multidimensional arrays --- src/Unirest/Request.php | 37 +++++++++++++++++++++-------------- tests/Unirest/RequestTest.php | 26 ++++++++++++------------ 2 files changed, 35 insertions(+), 28 deletions(-) diff --git a/src/Unirest/Request.php b/src/Unirest/Request.php index 5c8276b..2ad7b6d 100644 --- a/src/Unirest/Request.php +++ b/src/Unirest/Request.php @@ -121,12 +121,12 @@ class Request * Prepares a file for upload. To be used inside the parameters declaration for a request. * @param string $path The file path */ - public static function file($path) + public static function file($filename, $mimetype = '', $postname = '') { if (function_exists('curl_file_create')) { - return curl_file_create($path); + return curl_file_create($filename, $mimetype = '', $postname = ''); } else { - return '@' . $path; + return sprintf('@%s;filename=%s;type=%s', $filename, $postname ?: basename($filename), $mimetype); } } @@ -134,20 +134,29 @@ class Request * This function is useful for serializing multidimensional arrays, and avoid getting * the 'Array to string conversion' notice */ - public static function buildHTTPCurlQuery($arrays, &$new = array(), $prefix = null) + public static function buildHTTPCurlQuery($data, $parent = false) { - if (is_object($arrays)) { - $arrays = get_object_vars($arrays); + $result = array(); + + if (is_object($data)) { + $data = get_object_vars($data); } - foreach ($arrays as $key => $value) { - $k = isset($prefix) ? $prefix . '[' . $key . ']' : $key; - if (!$value instanceof \CURLFile and (is_array($value) or is_object($value))) { - self::buildHTTPCurlQuery($value, $new, $k); + foreach ($data as $key => $value) { + if ($parent) { + $new_key = sprintf('%s[%s]', $parent, $key); } else { - $new[$k] = $value; + $new_key = $key; + } + + if (!$value instanceof \CURLFile and (is_array($value) or is_object($value))) { + $result = array_merge($result, self::buildHTTPCurlQuery($value, $new_key)); + } else { + $result[$new_key] = $value; } } + + return $result; } /** @@ -189,8 +198,7 @@ class Request curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $method); if (is_array($body) || $body instanceof \Traversable) { - self::buildHTTPCurlQuery($body, $postBody); - curl_setopt($ch, CURLOPT_POSTFIELDS, $postBody); + curl_setopt($ch, CURLOPT_POSTFIELDS, self::buildHTTPCurlQuery($body)); } else { curl_setopt($ch, CURLOPT_POSTFIELDS, $body); } @@ -201,8 +209,7 @@ class Request $url .= '?'; } - self::buildHTTPCurlQuery($body, $postBody); - $url .= urldecode(http_build_query($postBody)); + $url .= urldecode(http_build_query(self::buildHTTPCurlQuery($body))); } curl_setopt($ch, CURLOPT_URL, self::encodeUrl($url)); diff --git a/tests/Unirest/RequestTest.php b/tests/Unirest/RequestTest.php index bb68c4a..7f1483b 100644 --- a/tests/Unirest/RequestTest.php +++ b/tests/Unirest/RequestTest.php @@ -195,6 +195,19 @@ class UnirestTest extends \PHPUnit_Framework_TestCase $this->assertEquals('Sam Sullivan', $json->author); } + public function testHttpBuildQueryWhenCurlFile() + { + $file = Request::file(UPLOAD_FIXTURE); + $body = array( + 'to' => 'mail@mailinator.com', + 'from' => 'mail@mailinator.com', + 'file' => $file + ); + + $result = Request::buildHTTPCurlQuery($body); + $this->assertEquals($result['file'], $file); + } + public function testUpload() { $response = Request::post('http://httpbin.org/post', array( @@ -369,17 +382,4 @@ class UnirestTest extends \PHPUnit_Framework_TestCase $headers = $response->body->headers; $this->assertEquals('ciao', $headers->{'User-Agent'}); } - - public function testHttpBuildQueryWhenCurlFile() - { - $file = Request::file(UPLOAD_FIXTURE); - $body = array( - 'to' => 'mail@mailinator.com', - 'from' => 'mail@mailinator.com', - 'file' => $file - ); - - Request::buildHTTPCurlQuery($body, $postBody); - $this->assertEquals($postBody['file'], $file); - } } From 87f5c54308582a121480f8269028915f7fa083b3 Mon Sep 17 00:00:00 2001 From: Ahmad Nassri Date: Thu, 18 Dec 2014 01:19:38 -0500 Subject: [PATCH 20/41] fixing travis build --- tests/Unirest/RequestTest.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tests/Unirest/RequestTest.php b/tests/Unirest/RequestTest.php index 7f1483b..f6c835b 100644 --- a/tests/Unirest/RequestTest.php +++ b/tests/Unirest/RequestTest.php @@ -1,6 +1,6 @@ Date: Tue, 13 Jan 2015 16:20:38 -0500 Subject: [PATCH 21/41] proper json formating --- composer.json | 56 +++++++++++++++++++++++++-------------------------- 1 file changed, 28 insertions(+), 28 deletions(-) diff --git a/composer.json b/composer.json index 8324c12..35d8647 100644 --- a/composer.json +++ b/composer.json @@ -1,31 +1,31 @@ { - "name" : "mashape/unirest-php", - "description" : "Unirest PHP", - "keywords" : ["rest", "curl", "http", "client"], - "type" : "library", - "homepage" : "https://github.com/Mashape/unirest-php", - "license" : "MIT", - "authors" : [ - { - "name" : "Mashape", - "email" : "support@mashape.com", - "homepage" : "http://mashape.com" - } - ], - "require" : { - "php" : ">=5.4.0", - "ext-curl" : "*", - "ext-json" : "*" - }, - "require-dev": { - "phpunit/phpunit": "*" - }, - "autoload" : { - "psr-0" : { - "Unirest" : "src" - } - }, - "support" : { - "email" : "support@mashape.com" + "name": "mashape/unirest-php", + "description": "Unirest PHP", + "keywords": ["rest", "curl", "http", "client"], + "type": "library", + "homepage": "https://github.com/Mashape/unirest-php", + "license": "MIT", + "authors": [ + { + "name": "Mashape", + "email": "support@mashape.com", + "homepage": "http://mashape.com" } + ], + "require": { + "php": ">=5.4.0", + "ext-curl": "*", + "ext-json": "*" + }, + "require-dev": { + "phpunit/phpunit": "*" + }, + "autoload": { + "psr-0": { + "Unirest": "src" + } + }, + "support": { + "email": "support@mashape.com" + } } From 2279d98f6a2ca14bece487174b1f66af5fa1a415 Mon Sep 17 00:00:00 2001 From: Ahmad Nassri Date: Tue, 13 Jan 2015 16:21:06 -0500 Subject: [PATCH 22/41] two whitespaces --- phpunit.xml | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/phpunit.xml b/phpunit.xml index 476064e..85f1e97 100644 --- a/phpunit.xml +++ b/phpunit.xml @@ -1,12 +1,12 @@ - - - ./tests - - + + + ./tests + + - - - + + + From f0b84f49ca31345ef13f9c24bc6fa12dfba8ff94 Mon Sep 17 00:00:00 2001 From: Ahmad Nassri Date: Tue, 13 Jan 2015 16:21:23 -0500 Subject: [PATCH 23/41] proper mashape url --- LICENSE | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/LICENSE b/LICENSE index d57c528..55f752f 100644 --- a/LICENSE +++ b/LICENSE @@ -1,6 +1,6 @@ The MIT License -Copyright (c) 2013 Mashape (http://mashape.com) +Copyright (c) 2013 Mashape (https://www.mashape.com) Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the From b4b4b85a6968cbddc9336087e560ebec239fb458 Mon Sep 17 00:00:00 2001 From: Ahmad Nassri Date: Tue, 13 Jan 2015 16:22:03 -0500 Subject: [PATCH 24/41] updating copyright year --- LICENSE | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/LICENSE b/LICENSE index 55f752f..78fe11e 100644 --- a/LICENSE +++ b/LICENSE @@ -1,6 +1,6 @@ The MIT License -Copyright (c) 2013 Mashape (https://www.mashape.com) +Copyright (c) 2013-2015 Mashape (https://www.mashape.com) Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the From 601c20c6ca6f58fe220207a17979885243003ba3 Mon Sep 17 00:00:00 2001 From: Ahmad Nassri Date: Wed, 14 Jan 2015 17:38:04 -0500 Subject: [PATCH 25/41] updating mashape url and email --- composer.json | 12 +++--------- 1 file changed, 3 insertions(+), 9 deletions(-) diff --git a/composer.json b/composer.json index 35d8647..b05334e 100644 --- a/composer.json +++ b/composer.json @@ -1,17 +1,11 @@ { "name": "mashape/unirest-php", "description": "Unirest PHP", - "keywords": ["rest", "curl", "http", "client"], + "keywords": ["rest", "curl", "http", "https", "client"], "type": "library", "homepage": "https://github.com/Mashape/unirest-php", "license": "MIT", - "authors": [ - { - "name": "Mashape", - "email": "support@mashape.com", - "homepage": "http://mashape.com" - } - ], + "author": "Mashape (https://www.mashape.com)", "require": { "php": ">=5.4.0", "ext-curl": "*", @@ -26,6 +20,6 @@ } }, "support": { - "email": "support@mashape.com" + "email": "opensource@mashape.com" } } From 2bbafd950d9b4005ef215ff7106ab7ed600c66af Mon Sep 17 00:00:00 2001 From: Ahmad Nassri Date: Wed, 14 Jan 2015 17:46:52 -0500 Subject: [PATCH 26/41] updating editorconfig settings --- .editorconfig | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/.editorconfig b/.editorconfig index 09459e5..971de2d 100644 --- a/.editorconfig +++ b/.editorconfig @@ -9,8 +9,8 @@ charset = utf-8 trim_trailing_whitespace = true insert_final_newline = true -[*.md] -trim_trailing_whitespace = false +[*.{json,xml,yml}] +indent_size = 2 -[*.yml] +[*.{md,yml}] trim_trailing_whitespace = false From 34db4e958f8de19e255dcad3a1525d0d10257569 Mon Sep 17 00:00:00 2001 From: Ahmad Nassri Date: Wed, 14 Jan 2015 17:47:20 -0500 Subject: [PATCH 27/41] spacing cleanup --- .gitignore | 4 ++-- .scrutinizer.yml | 24 ++++++++++++------------ 2 files changed, 14 insertions(+), 14 deletions(-) diff --git a/.gitignore b/.gitignore index 9667df9..922ede7 100644 --- a/.gitignore +++ b/.gitignore @@ -1,4 +1,4 @@ .DS_Store -/vendor +vendor composer.lock -composer.phar \ No newline at end of file +composer.phar diff --git a/.scrutinizer.yml b/.scrutinizer.yml index 3e6cc9d..0a46bf9 100644 --- a/.scrutinizer.yml +++ b/.scrutinizer.yml @@ -1,15 +1,15 @@ tools: - php_sim: true - php_pdepend: true - php_analyzer: true - php_mess_detector: true - php_changetracking: true - sensiolabs_security_checker: true + php_sim: true + php_pdepend: true + php_analyzer: true + php_mess_detector: true + php_changetracking: true + sensiolabs_security_checker: true - php_code_sniffer: - config: - standard: 'PSR2' + php_code_sniffer: + config: + standard: 'PSR2' - php_cs_fixer: - config: - level: 'psr2' + php_cs_fixer: + config: + level: 'psr2' From 7a6df4cb82c234bed82be2876d601fd9e114d7fe Mon Sep 17 00:00:00 2001 From: Ahmad Nassri Date: Wed, 14 Jan 2015 18:07:10 -0500 Subject: [PATCH 28/41] adding the full scope of the HTTP Methods registery --- src/Unirest/Method.php | 70 ++++++++++++++++++++++++++++++++++++++++-- 1 file changed, 68 insertions(+), 2 deletions(-) diff --git a/src/Unirest/Method.php b/src/Unirest/Method.php index 0076a31..bd2df20 100644 --- a/src/Unirest/Method.php +++ b/src/Unirest/Method.php @@ -1,12 +1,78 @@ Date: Wed, 14 Jan 2015 18:15:13 -0500 Subject: [PATCH 29/41] updating Request utility methods to match all of RFC7231 --- src/Unirest/Request.php | 56 +++++++++++++++++++++++++++++++++++++++++ 1 file changed, 56 insertions(+) diff --git a/src/Unirest/Request.php b/src/Unirest/Request.php index 2ad7b6d..fd67ba9 100644 --- a/src/Unirest/Request.php +++ b/src/Unirest/Request.php @@ -61,6 +61,48 @@ class Request return self::send(Method::GET, $url, $parameters, $headers, $username, $password); } + /** + * Send a HEAD request to a URL + * @param string $url URL to send the HEAD request to + * @param array $headers additional headers to send + * @param mixed $parameters parameters to send in the querystring + * @param string $username Basic Authentication username + * @param string $password Basic Authentication password + * @return string|stdObj response string or stdObj if response is json-decodable + */ + public static function head($url, $headers = array(), $parameters = null, $username = null, $password = null) + { + return self::send(Method::HEAD, $url, $parameters, $headers, $username, $password); + } + + /** + * Send a OPTIONS request to a URL + * @param string $url URL to send the OPTIONS request to + * @param array $headers additional headers to send + * @param mixed $parameters parameters to send in the querystring + * @param string $username Basic Authentication username + * @param string $password Basic Authentication password + * @return string|stdObj response string or stdObj if response is json-decodable + */ + public static function options($url, $headers = array(), $parameters = null, $username = null, $password = null) + { + return self::send(Method::OPTIONS, $url, $parameters, $headers, $username, $password); + } + + /** + * Send a CONNECT request to a URL + * @param string $url URL to send the CONNECT request to + * @param array $headers additional headers to send + * @param mixed $parameters parameters to send in the querystring + * @param string $username Basic Authentication username + * @param string $password Basic Authentication password + * @return string|stdObj response string or stdObj if response is json-decodable + */ + public static function connect($url, $headers = array(), $parameters = null, $username = null, $password = null) + { + return self::send(Method::CONNECT, $url, $parameters, $headers, $username, $password); + } + /** * Send POST request to a URL * @param string $url URL to send the POST request to @@ -117,6 +159,20 @@ class Request return self::send(Method::PATCH, $url, $body, $headers, $username, $password); } + /** + * Send TRACE request to a URL + * @param string $url URL to send the TRACE request to + * @param array $headers additional headers to send + * @param mixed $body TRACE body data + * @param string $username Basic Authentication username + * @param string $password Basic Authentication password + * @return string|stdObj response string or stdObj if response is json-decodable + */ + public static function trace($url, $headers = array(), $body = null, $username = null, $password = null) + { + return self::send(Method::TRACE, $url, $body, $headers, $username, $password); + } + /** * Prepares a file for upload. To be used inside the parameters declaration for a request. * @param string $path The file path From be9bca1d5aeb797f43b82293fa50fa3f91b49107 Mon Sep 17 00:00:00 2001 From: Ahmad Nassri Date: Wed, 14 Jan 2015 18:31:21 -0500 Subject: [PATCH 30/41] splitting out Unirest\File and updating README --- README.md | 82 +++++++++++++++++------------------ src/Unirest.php | 1 + src/Unirest/File.php | 19 ++++++++ src/Unirest/Method.php | 3 -- src/Unirest/Request.php | 13 ------ src/Unirest/Response.php | 4 +- tests/Unirest/RequestTest.php | 8 ++-- 7 files changed, 64 insertions(+), 66 deletions(-) create mode 100644 src/Unirest/File.php diff --git a/README.md b/README.md index ffff4a9..6a06281 100644 --- a/README.md +++ b/README.md @@ -2,38 +2,38 @@ Unirest is a set of lightweight HTTP libraries available in multiple languages, ideal for most applications: -* Make `GET`, `POST`, `PUT`, `PATCH`, `DELETE` requests -* It supports form parameters, file uploads and custom body entities +* Utility methods to call `GET`, `HEAD`, `POST`, `PUT`, `DELETE`, `CONNECT`, `OPTIONS`, `TRACE`, `PATCH` requests +* Supports form parameters, file uploads and custom body entities * Supports gzip * Supports Basic Authentication natively * Customizable timeout * Customizable default headers for every request (DRY) * Automatic JSON parsing into a native object for JSON responses -Created with love by [thefosk](https://github.com/thefosk) @ [mashape.com](https://mashape.com) +Created with love by [Mashape](https://www.mashape.com) --- -**To the community**: At this time Unirest-PHP only support syncronous requests, and I would really love to implement asynchronous support. If you guys have any feedback or ideas please comment on issue #23. +**To the community**: At this time Unirest-PHP only support syncronous requests, and I would really love to implement asynchronous support. If you guys have any feedback or ideas please comment on issue [#23](https://github.com/Mashape/unirest-php/issues/23). --- ### Install with Composer -If you're using [Composer](https://github.com/composer/composer) to manage -dependencies, you can add Unirest with it. +If you're using [Composer](https://getcomposer.org/) to manage dependencies, you can add Unirest with it. ```javascript { "require" : { - "mashape/unirest-php" : "dev-master" + "mashape/unirest-php" : "2.0.*" }, "autoload": { - "psr-0": {"Unirest": "lib/"} + "psr-0": {"Unirest": "src/"} } } ``` ### Install source from GitHub + Unirest-PHP requires PHP `v5.3+`. Download the PHP library from Github, and require in your script like so: To install the source code: @@ -45,7 +45,7 @@ $ git clone git@github.com:Mashape/unirest-php.git And include it in your scripts: ```bash -require_once '/path/to/unirest-php/lib/Unirest.php'; +require_once '/path/to/unirest-php/src/Unirest.php'; ``` ## Creating Request @@ -53,17 +53,15 @@ require_once '/path/to/unirest-php/lib/Unirest.php'; So you're probably wondering how using Unirest makes creating requests in PHP easier, let's look at a working example: ```php -$response = Unirest::post("http://httpbin.org/post", array( "Accept" => "application/json" ), - array( - "parameter" => 23, - "foo" => "bar" - ) -); +$headers = array("Accept" => "application/json"); +$body = array("foo" => "hellow", "bar" => "world"); -$response->code; // HTTP Status code -$response->headers; // Headers -$response->body; // Parsed body -$response->raw_body; // Unparsed body +$response = Unirest\Request::post("http://httpbin.org/post", $headers, $body); + +$response->code; // HTTP Status code +$response->headers; // Headers +$response->body; // Parsed body +$response->raw_body; // Unparsed body ``` ### File Uploads @@ -71,24 +69,20 @@ $response->raw_body; // Unparsed body To upload files in a multipart form representation use the return value of `Unirest::file($path)` as the value of a parameter: ```php -$response = Unirest::post("http://httpbin.org/post", array( "Accept" => "application/json" ), - array( - "file" => Unirest::file("/tmp/file.txt") // Tells Unirest where the file is located - ) -); +$headers = array("Accept" => "application/json"); +$body = array("file" => Unirest\File::add("/tmp/file.txt")); + +$response = Unirest\Request::post("http://httpbin.org/post", $headers, $body); ``` ### Custom Entity Body + Sending a custom body such as a JSON Object rather than a string or form style parameters we utilize json_encode for the body: ```php -$response = Unirest::post("http://httpbin.org/post", array( "Accept" => "application/json" ), - json_encode( - array( - "parameter" => "value", - "foo" => "bar" - ) - ) -); +$headers = array("Accept" => "application/json"); +$body = json_encode(array("foo" => "hellow", "bar" => "world")); + +$response = Unirest\Request::post("http://httpbin.org/post", $headers, $body); ``` ### Basic Authentication @@ -96,16 +90,17 @@ $response = Unirest::post("http://httpbin.org/post", array( "Accept" => "applica Authenticating the request with basic authentication can be done by providing the `username` and `password` arguments: ```php -$response = Unirest::get("http://httpbin.org/get", null, null, "username", "password"); +$response = Unirest\Request::get("http://httpbin.org/get", null, null, "username", "password"); ``` # Request + ```php -Unirest::get($url, $headers = array(), $parameters = NULL, $username = NULL, $password = NULL) -Unirest::post($url, $headers = array(), $body = NULL, $username = NULL, $password = NULL) -Unirest::put($url, $headers = array(), $body = NULL, $username = NULL, $password = NULL) -Unirest::patch($url, $headers = array(), $body = NULL, $username = NULL, $password = NULL) -Unirest::delete($url, $headers = array(), $body = NULL, $username = NULL, $password = NULL) +Unirest\Request::get($url, $headers = array(), $parameters = NULL, $username = NULL, $password = NULL) +Unirest\Request::post($url, $headers = array(), $body = NULL, $username = NULL, $password = NULL) +Unirest\Request::put($url, $headers = array(), $body = NULL, $username = NULL, $password = NULL) +Unirest\Request::patch($url, $headers = array(), $body = NULL, $username = NULL, $password = NULL) +Unirest\Request::delete($url, $headers = array(), $body = NULL, $username = NULL, $password = NULL) ``` - `url` - Endpoint, address, or uri to be acted upon and requested information from. @@ -115,6 +110,7 @@ Unirest::delete($url, $headers = array(), $body = NULL, $username = NULL, $passw - `password` - Basic Authentication password # Response + Upon recieving a response Unirest returns the result in the form of an Object, this object should always have the same keys for each language regarding to the response details. - `code` - HTTP Response Status Code (Example `200`) @@ -131,7 +127,7 @@ You can set some advanced configuration to tune Unirest-PHP: You can set a custom timeout value (in **seconds**): ```php -Unirest::timeout(5); // 5s timeout +Unirest\Request::timeout(5); // 5s timeout ``` ### Default Request Headers @@ -139,14 +135,14 @@ Unirest::timeout(5); // 5s timeout You can set default headers that will be sent on every request: ```php -Unirest::defaultHeader("Header1", "Value1"); -Unirest::defaultHeader("Header2", "Value2"); +Unirest\Request::defaultHeader("Header1", "Value1"); +Unirest\Request::defaultHeader("Header2", "Value2"); ``` You can clear the default headers anytime with: ```php -Unirest::clearDefaultHeaders(); +Unirest\Request::clearDefaultHeaders(); ``` ### SSL validation @@ -154,7 +150,7 @@ Unirest::clearDefaultHeaders(); You can explicitly enable or disable SSL certificate validation when consuming an SSL protected endpoint: ```php -Unirest::verifyPeer(false); // Disables SSL cert validation +Unirest\Request::verifyPeer(false); // Disables SSL cert validation ``` By default is `true`. diff --git a/src/Unirest.php b/src/Unirest.php index a2d0a5a..a75eb85 100644 --- a/src/Unirest.php +++ b/src/Unirest.php @@ -1,5 +1,6 @@ $h) { $h = explode(':', $h, 2); diff --git a/tests/Unirest/RequestTest.php b/tests/Unirest/RequestTest.php index f6c835b..c1cc523 100644 --- a/tests/Unirest/RequestTest.php +++ b/tests/Unirest/RequestTest.php @@ -4,11 +4,11 @@ require_once __DIR__ . '/../../src/Unirest.php'; define('UPLOAD_FIXTURE', dirname(__DIR__) . '/fixtures/upload.txt'); +use Unirest\File as File; use Unirest\Request as Request; class UnirestTest extends \PHPUnit_Framework_TestCase { - public function testGet() { $response = Request::get('http://httpbin.org/get?name=Mark', array( @@ -197,7 +197,7 @@ class UnirestTest extends \PHPUnit_Framework_TestCase public function testHttpBuildQueryWhenCurlFile() { - $file = Request::file(UPLOAD_FIXTURE); + $file = File::add(UPLOAD_FIXTURE); $body = array( 'to' => 'mail@mailinator.com', 'from' => 'mail@mailinator.com', @@ -214,7 +214,7 @@ class UnirestTest extends \PHPUnit_Framework_TestCase 'Accept' => 'application/json' ), array( 'name' => 'Mark', - 'file' => Request::file(UPLOAD_FIXTURE) + 'file' => File::add(UPLOAD_FIXTURE) )); $this->assertEquals(200, $response->code); @@ -231,7 +231,7 @@ class UnirestTest extends \PHPUnit_Framework_TestCase 'Accept' => 'application/json' ), array( 'name' => 'Mark', - 'files[owl.gif]' => Request::file(UPLOAD_FIXTURE) + 'files[owl.gif]' => File::add(UPLOAD_FIXTURE) )); $this->assertEquals(200, $response->code); From 4f156e59fdf11766f8c759a1a3eff7751cfc2dbf Mon Sep 17 00:00:00 2001 From: Ahmad Nassri Date: Wed, 14 Jan 2015 18:40:21 -0500 Subject: [PATCH 31/41] improving tests --- phpunit.xml | 2 +- tests/Unirest/FileTest.php | 12 ++++++ tests/Unirest/RequestTest.php | 81 ++++++++++++++++------------------- tests/bootstrap.php | 5 +++ 4 files changed, 55 insertions(+), 45 deletions(-) create mode 100644 tests/Unirest/FileTest.php create mode 100644 tests/bootstrap.php diff --git a/phpunit.xml b/phpunit.xml index 85f1e97..fe1ce82 100644 --- a/phpunit.xml +++ b/phpunit.xml @@ -1,5 +1,5 @@ - + ./tests diff --git a/tests/Unirest/FileTest.php b/tests/Unirest/FileTest.php new file mode 100644 index 0000000..525f074 --- /dev/null +++ b/tests/Unirest/FileTest.php @@ -0,0 +1,12 @@ +assertTrue($file instanceof \CURLFile); + } +} diff --git a/tests/Unirest/RequestTest.php b/tests/Unirest/RequestTest.php index c1cc523..732f2f2 100644 --- a/tests/Unirest/RequestTest.php +++ b/tests/Unirest/RequestTest.php @@ -1,17 +1,10 @@ 'application/json' ), array( 'nick' => 'thefosk' @@ -26,7 +19,7 @@ class UnirestTest extends \PHPUnit_Framework_TestCase public function testGetMultidimensionalArray() { - $response = Request::get('http://httpbin.org/get', array( + $response = Unirest\Request::get('http://httpbin.org/get', array( 'Accept' => 'application/json' ), array( 'key' => 'value', @@ -47,7 +40,7 @@ class UnirestTest extends \PHPUnit_Framework_TestCase public function testGetWithDots() { - $response = Request::get('http://httpbin.org/get', array( + $response = Unirest\Request::get('http://httpbin.org/get', array( 'Accept' => 'application/json' ), array( 'user.name' => 'Mark', @@ -63,7 +56,7 @@ class UnirestTest extends \PHPUnit_Framework_TestCase public function testGetWithDots2() { - $response = Request::get('http://httpbin.org/get', array( + $response = Unirest\Request::get('http://httpbin.org/get', array( 'Accept' => 'application/json' ), array( 'user.name' => 'Mark Bond', @@ -79,7 +72,7 @@ class UnirestTest extends \PHPUnit_Framework_TestCase public function testPost() { - $response = Request::post('http://httpbin.org/post', array( + $response = Unirest\Request::post('http://httpbin.org/post', array( 'Accept' => 'application/json' ), array( 'name' => 'Mark', @@ -95,7 +88,7 @@ class UnirestTest extends \PHPUnit_Framework_TestCase public function testPostWithEqualSign() { - $response = Request::post('http://httpbin.org/post', array( + $response = Unirest\Request::post('http://httpbin.org/post', array( 'Accept' => 'application/json' ), array( 'name' => 'Mark=Hello' @@ -109,7 +102,7 @@ class UnirestTest extends \PHPUnit_Framework_TestCase public function testGetWithEqualSign() { - $response = Request::get('http://httpbin.org/get', array( + $response = Unirest\Request::get('http://httpbin.org/get', array( 'Accept' => 'application/json' ), array( 'name' => 'Mark=Hello' @@ -120,7 +113,7 @@ class UnirestTest extends \PHPUnit_Framework_TestCase $args = $response->body->args; $this->assertEquals('Mark=Hello', $args->name); - $response = Request::get('http://httpbin.org/get', array( + $response = Unirest\Request::get('http://httpbin.org/get', array( 'Accept' => 'application/json' ), array( 'name' => 'Mark=Hello=John' @@ -134,7 +127,7 @@ class UnirestTest extends \PHPUnit_Framework_TestCase public function testPostArray() { - $response = Request::post('http://httpbin.org/post', array( + $response = Unirest\Request::post('http://httpbin.org/post', array( 'Accept' => 'application/json' ), array( 'name[0]' => 'Mark', @@ -151,7 +144,7 @@ class UnirestTest extends \PHPUnit_Framework_TestCase public function testGetArray() { - $response = Request::get('http://httpbin.org/get', array(), array( + $response = Unirest\Request::get('http://httpbin.org/get', array(), array( 'name[0]' => 'Mark', 'name[1]' => 'John' )); @@ -165,7 +158,7 @@ class UnirestTest extends \PHPUnit_Framework_TestCase public function testPostWithDots() { - $response = Request::post('http://httpbin.org/post', array( + $response = Unirest\Request::post('http://httpbin.org/post', array( 'Accept' => 'application/json' ), array( 'user.name' => 'Mark', @@ -181,7 +174,7 @@ class UnirestTest extends \PHPUnit_Framework_TestCase public function testRawPost() { - $response = Request::post('http://httpbin.org/post', array( + $response = Unirest\Request::post('http://httpbin.org/post', array( 'Accept' => 'application/json', 'Content-Type' => 'application/json' ), json_encode(array( @@ -197,24 +190,24 @@ class UnirestTest extends \PHPUnit_Framework_TestCase public function testHttpBuildQueryWhenCurlFile() { - $file = File::add(UPLOAD_FIXTURE); + $file = Unirest\File::add(UPLOAD_FIXTURE); $body = array( 'to' => 'mail@mailinator.com', 'from' => 'mail@mailinator.com', 'file' => $file ); - $result = Request::buildHTTPCurlQuery($body); + $result = Unirest\Request::buildHTTPCurlQuery($body); $this->assertEquals($result['file'], $file); } public function testUpload() { - $response = Request::post('http://httpbin.org/post', array( + $response = Unirest\Request::post('http://httpbin.org/post', array( 'Accept' => 'application/json' ), array( 'name' => 'Mark', - 'file' => File::add(UPLOAD_FIXTURE) + 'file' => Unirest\File::add(UPLOAD_FIXTURE) )); $this->assertEquals(200, $response->code); @@ -227,11 +220,11 @@ class UnirestTest extends \PHPUnit_Framework_TestCase public function testUploadIfFilePartOfData() { - $response = Request::post('http://httpbin.org/post', array( + $response = Unirest\Request::post('http://httpbin.org/post', array( 'Accept' => 'application/json' ), array( 'name' => 'Mark', - 'files[owl.gif]' => File::add(UPLOAD_FIXTURE) + 'files[owl.gif]' => Unirest\File::add(UPLOAD_FIXTURE) )); $this->assertEquals(200, $response->code); @@ -244,7 +237,7 @@ class UnirestTest extends \PHPUnit_Framework_TestCase public function testPostMultidimensionalArray() { - $response = Request::post('http://httpbin.org/post', array( + $response = Unirest\Request::post('http://httpbin.org/post', array( 'Accept' => 'application/json' ), array( 'key' => 'value', @@ -264,7 +257,7 @@ class UnirestTest extends \PHPUnit_Framework_TestCase public function testPut() { - $response = Request::put('http://httpbin.org/put', array( + $response = Unirest\Request::put('http://httpbin.org/put', array( 'Accept' => 'application/json' ), array( 'name' => 'Mark', @@ -280,7 +273,7 @@ class UnirestTest extends \PHPUnit_Framework_TestCase public function testPatch() { - $response = Request::patch('http://httpbin.org/patch', array( + $response = Unirest\Request::patch('http://httpbin.org/patch', array( 'Accept' => 'application/json' ), array( 'name' => 'Mark', @@ -296,7 +289,7 @@ class UnirestTest extends \PHPUnit_Framework_TestCase public function testDelete() { - $response = Request::delete('http://httpbin.org/delete', array( + $response = Unirest\Request::delete('http://httpbin.org/delete', array( 'Accept' => 'application/json', 'Content-Type' => 'application/x-www-form-urlencoded' ), array( @@ -314,42 +307,42 @@ class UnirestTest extends \PHPUnit_Framework_TestCase */ public function testTimeoutFail() { - Request::timeout(1); + Unirest\Request::timeout(1); - Request::get('http://httpbin.org/delay/3'); + Unirest\Request::get('http://httpbin.org/delay/3'); - Request::timeout(null); // Cleaning timeout for the other tests + Unirest\Request::timeout(null); // Cleaning timeout for the other tests } public function testTimeoutSuccess() { - Request::timeout(3); + Unirest\Request::timeout(3); - $response = Request::get('http://httpbin.org/delay/1'); + $response = Unirest\Request::get('http://httpbin.org/delay/1'); $this->assertEquals(200, $response->code); - Request::timeout(null); // Cleaning timeout for the other tests + Unirest\Request::timeout(null); // Cleaning timeout for the other tests } public function testDefaultHeader() { - Request::defaultHeader('Hello', 'custom'); - $response = Request::get('http://httpbin.org/get'); + Unirest\Request::defaultHeader('Hello', 'custom'); + $response = Unirest\Request::get('http://httpbin.org/get'); $this->assertEquals(200, $response->code); $headers = $response->body->headers; $properties = get_object_vars($headers); $this->assertTrue(array_key_exists('Hello', $properties)); $this->assertEquals('custom', $headers->Hello); - $response = Request::get('http://httpbin.org/get'); + $response = Unirest\Request::get('http://httpbin.org/get'); $this->assertEquals(200, $response->code); $headers = $response->body->headers; $properties = get_object_vars($headers); $this->assertTrue(array_key_exists('Hello', $properties)); $this->assertEquals('custom', $headers->Hello); - Request::clearDefaultHeaders(); - $response = Request::get('http://httpbin.org/get'); + Unirest\Request::clearDefaultHeaders(); + $response = Unirest\Request::get('http://httpbin.org/get'); $this->assertEquals(200, $response->code); $headers = $response->body->headers; @@ -359,21 +352,21 @@ class UnirestTest extends \PHPUnit_Framework_TestCase public function testGzip() { - $response = Request::get('http://httpbin.org/gzip'); + $response = Unirest\Request::get('http://httpbin.org/gzip'); $args = $response->body; $this->assertEquals(true, $args->gzipped); } public function testBasicAuthentication() { - $response = Request::get('http://httpbin.org/get', array(), array(), 'user', 'password'); + $response = Unirest\Request::get('http://httpbin.org/get', array(), array(), 'user', 'password'); $headers = $response->body->headers; $this->assertEquals('Basic dXNlcjpwYXNzd29yZA==', $headers->Authorization); } public function testCustomHeaders() { - $response = Request::get('http://httpbin.org/get', array( + $response = Unirest\Request::get('http://httpbin.org/get', array( 'user-agent' => 'ciao', )); diff --git a/tests/bootstrap.php b/tests/bootstrap.php new file mode 100644 index 0000000..1753d82 --- /dev/null +++ b/tests/bootstrap.php @@ -0,0 +1,5 @@ + Date: Wed, 14 Jan 2015 18:44:05 -0500 Subject: [PATCH 32/41] just some ordering --- tests/Unirest/RequestTest.php | 581 +++++++++++++++++----------------- 1 file changed, 294 insertions(+), 287 deletions(-) diff --git a/tests/Unirest/RequestTest.php b/tests/Unirest/RequestTest.php index 732f2f2..00a68aa 100644 --- a/tests/Unirest/RequestTest.php +++ b/tests/Unirest/RequestTest.php @@ -2,192 +2,7 @@ class UnirestRequestTest extends \PHPUnit_Framework_TestCase { - public function testGet() - { - $response = Unirest\Request::get('http://httpbin.org/get?name=Mark', array( - 'Accept' => 'application/json' - ), array( - 'nick' => 'thefosk' - )); - - $this->assertEquals(200, $response->code); - - $args = $response->body->args; - $this->assertEquals('Mark', $args->name); - $this->assertEquals('thefosk', $args->nick); - } - - public function testGetMultidimensionalArray() - { - $response = Unirest\Request::get('http://httpbin.org/get', array( - 'Accept' => 'application/json' - ), array( - 'key' => 'value', - 'items' => array( - 'item1', - 'item2' - ) - )); - - $this->assertEquals(200, $response->code); - - $args = $response->body->args; - - $this->assertEquals('value', $args->key); - $this->assertEquals('item1', $args->{'items[0]'}); - $this->assertEquals('item2', $args->{'items[1]'}); - } - - public function testGetWithDots() - { - $response = Unirest\Request::get('http://httpbin.org/get', array( - 'Accept' => 'application/json' - ), array( - 'user.name' => 'Mark', - 'nick' => 'thefosk' - )); - - $this->assertEquals(200, $response->code); - - $args = $response->body->args; - $this->assertEquals('Mark', $args->{'user.name'}); - $this->assertEquals('thefosk', $args->nick); - } - - public function testGetWithDots2() - { - $response = Unirest\Request::get('http://httpbin.org/get', array( - 'Accept' => 'application/json' - ), array( - 'user.name' => 'Mark Bond', - 'nick' => 'thefosk' - )); - - $this->assertEquals(200, $response->code); - - $args = $response->body->args; - $this->assertEquals('Mark Bond', $args->{'user.name'}); - $this->assertEquals('thefosk', $args->nick); - } - - public function testPost() - { - $response = Unirest\Request::post('http://httpbin.org/post', array( - 'Accept' => 'application/json' - ), array( - 'name' => 'Mark', - 'nick' => 'thefosk' - )); - - $this->assertEquals(200, $response->code); - - $form = $response->body->form; - $this->assertEquals('Mark', $form->name); - $this->assertEquals('thefosk', $form->nick); - } - - public function testPostWithEqualSign() - { - $response = Unirest\Request::post('http://httpbin.org/post', array( - 'Accept' => 'application/json' - ), array( - 'name' => 'Mark=Hello' - )); - - $this->assertEquals(200, $response->code); - - $form = $response->body->form; - $this->assertEquals('Mark=Hello', $form->name); - } - - public function testGetWithEqualSign() - { - $response = Unirest\Request::get('http://httpbin.org/get', array( - 'Accept' => 'application/json' - ), array( - 'name' => 'Mark=Hello' - )); - - $this->assertEquals(200, $response->code); - - $args = $response->body->args; - $this->assertEquals('Mark=Hello', $args->name); - - $response = Unirest\Request::get('http://httpbin.org/get', array( - 'Accept' => 'application/json' - ), array( - 'name' => 'Mark=Hello=John' - )); - - $this->assertEquals(200, $response->code); - - $args = $response->body->args; - $this->assertEquals('Mark=Hello=John', $args->name); - } - - public function testPostArray() - { - $response = Unirest\Request::post('http://httpbin.org/post', array( - 'Accept' => 'application/json' - ), array( - 'name[0]' => 'Mark', - 'name[1]' => 'John' - )); - - $this->assertEquals(200, $response->code); - - $form = $response->body->form; - - $this->assertEquals('Mark', $form->{'name[0]'}); - $this->assertEquals('John', $form->{'name[1]'}); - } - - public function testGetArray() - { - $response = Unirest\Request::get('http://httpbin.org/get', array(), array( - 'name[0]' => 'Mark', - 'name[1]' => 'John' - )); - - $this->assertEquals(200, $response->code); - - $args = $response->body->args; - $this->assertEquals('Mark', $args->{'name[0]'}); - $this->assertEquals('John', $args->{'name[1]'}); - } - - public function testPostWithDots() - { - $response = Unirest\Request::post('http://httpbin.org/post', array( - 'Accept' => 'application/json' - ), array( - 'user.name' => 'Mark', - 'nick' => 'thefosk' - )); - - $this->assertEquals(200, $response->code); - - $form = $response->body->form; - $this->assertEquals('Mark', $form->{'user.name'}); - $this->assertEquals('thefosk', $form->nick); - } - - public function testRawPost() - { - $response = Unirest\Request::post('http://httpbin.org/post', array( - 'Accept' => 'application/json', - 'Content-Type' => 'application/json' - ), json_encode(array( - 'author' => 'Sam Sullivan' - ))); - - $this->assertEquals(200, $response->code); - - $json = $response->body->json; - - $this->assertEquals('Sam Sullivan', $json->author); - } - + // Generic public function testHttpBuildQueryWhenCurlFile() { $file = Unirest\File::add(UPLOAD_FIXTURE); @@ -201,107 +16,6 @@ class UnirestRequestTest extends \PHPUnit_Framework_TestCase $this->assertEquals($result['file'], $file); } - public function testUpload() - { - $response = Unirest\Request::post('http://httpbin.org/post', array( - 'Accept' => 'application/json' - ), array( - 'name' => 'Mark', - 'file' => Unirest\File::add(UPLOAD_FIXTURE) - )); - $this->assertEquals(200, $response->code); - - $files = $response->body->files; - $this->assertEquals('This is a test', $files->file); - - $form = $response->body->form; - $this->assertEquals('Mark', $form->name); - } - - public function testUploadIfFilePartOfData() - { - $response = Unirest\Request::post('http://httpbin.org/post', array( - 'Accept' => 'application/json' - ), array( - 'name' => 'Mark', - 'files[owl.gif]' => Unirest\File::add(UPLOAD_FIXTURE) - )); - $this->assertEquals(200, $response->code); - - //$files = $response->body->files; - //$this->assertEquals('This is a test', $files->file); - - $form = $response->body->form; - $this->assertEquals('Mark', $form->name); - } - - public function testPostMultidimensionalArray() - { - $response = Unirest\Request::post('http://httpbin.org/post', array( - 'Accept' => 'application/json' - ), array( - 'key' => 'value', - 'items' => array( - 'item1', - 'item2' - ) - )); - - $this->assertEquals(200, $response->code); - - $form = $response->body->form; - $this->assertEquals('value', $form->key); - $this->assertEquals('item1', $form->{'items[0]'}); - $this->assertEquals('item2', $form->{'items[1]'}); - } - - public function testPut() - { - $response = Unirest\Request::put('http://httpbin.org/put', array( - 'Accept' => 'application/json' - ), array( - 'name' => 'Mark', - 'nick' => 'thefosk' - )); - - $this->assertEquals(200, $response->code); - - $form = $response->body->form; - $this->assertEquals('Mark', $form->name); - $this->assertEquals('thefosk', $form->nick); - } - - public function testPatch() - { - $response = Unirest\Request::patch('http://httpbin.org/patch', array( - 'Accept' => 'application/json' - ), array( - 'name' => 'Mark', - 'nick' => 'thefosk' - )); - - $this->assertEquals(200, $response->code); - - $form = $response->body->form; - $this->assertEquals('Mark', $form->name); - $this->assertEquals('thefosk', $form->nick); - } - - public function testDelete() - { - $response = Unirest\Request::delete('http://httpbin.org/delete', array( - 'Accept' => 'application/json', - 'Content-Type' => 'application/x-www-form-urlencoded' - ), array( - 'name' => 'Mark', - 'nick' => 'thefosk' - )); - - $this->assertEquals(200, $response->code); - $data = $response->body->data; - $this->assertTrue(empty($data)); - } - /** * @expectedException Exception */ @@ -375,4 +89,297 @@ class UnirestRequestTest extends \PHPUnit_Framework_TestCase $headers = $response->body->headers; $this->assertEquals('ciao', $headers->{'User-Agent'}); } + + // GET + public function testGet() + { + $response = Unirest\Request::get('http://httpbin.org/get?name=Mark', array( + 'Accept' => 'application/json' + ), array( + 'nick' => 'thefosk' + )); + + $this->assertEquals(200, $response->code); + + $args = $response->body->args; + $this->assertEquals('Mark', $args->name); + $this->assertEquals('thefosk', $args->nick); + } + + public function testGetMultidimensionalArray() + { + $response = Unirest\Request::get('http://httpbin.org/get', array( + 'Accept' => 'application/json' + ), array( + 'key' => 'value', + 'items' => array( + 'item1', + 'item2' + ) + )); + + $this->assertEquals(200, $response->code); + + $args = $response->body->args; + + $this->assertEquals('value', $args->key); + $this->assertEquals('item1', $args->{'items[0]'}); + $this->assertEquals('item2', $args->{'items[1]'}); + } + + public function testGetWithDots() + { + $response = Unirest\Request::get('http://httpbin.org/get', array( + 'Accept' => 'application/json' + ), array( + 'user.name' => 'Mark', + 'nick' => 'thefosk' + )); + + $this->assertEquals(200, $response->code); + + $args = $response->body->args; + $this->assertEquals('Mark', $args->{'user.name'}); + $this->assertEquals('thefosk', $args->nick); + } + + public function testGetWithDotsAlt() + { + $response = Unirest\Request::get('http://httpbin.org/get', array( + 'Accept' => 'application/json' + ), array( + 'user.name' => 'Mark Bond', + 'nick' => 'thefosk' + )); + + $this->assertEquals(200, $response->code); + + $args = $response->body->args; + $this->assertEquals('Mark Bond', $args->{'user.name'}); + $this->assertEquals('thefosk', $args->nick); + } + + public function testGetWithEqualSign() + { + $response = Unirest\Request::get('http://httpbin.org/get', array( + 'Accept' => 'application/json' + ), array( + 'name' => 'Mark=Hello' + )); + + $this->assertEquals(200, $response->code); + + $args = $response->body->args; + $this->assertEquals('Mark=Hello', $args->name); + + $response = Unirest\Request::get('http://httpbin.org/get', array( + 'Accept' => 'application/json' + ), array( + 'name' => 'Mark=Hello=John' + )); + + $this->assertEquals(200, $response->code); + + $args = $response->body->args; + $this->assertEquals('Mark=Hello=John', $args->name); + } + + public function testGetArray() + { + $response = Unirest\Request::get('http://httpbin.org/get', array(), array( + 'name[0]' => 'Mark', + 'name[1]' => 'John' + )); + + $this->assertEquals(200, $response->code); + + $args = $response->body->args; + $this->assertEquals('Mark', $args->{'name[0]'}); + $this->assertEquals('John', $args->{'name[1]'}); + } + + // POST + public function testPost() + { + $response = Unirest\Request::post('http://httpbin.org/post', array( + 'Accept' => 'application/json' + ), array( + 'name' => 'Mark', + 'nick' => 'thefosk' + )); + + $this->assertEquals(200, $response->code); + + $form = $response->body->form; + $this->assertEquals('Mark', $form->name); + $this->assertEquals('thefosk', $form->nick); + } + + public function testPostWithEqualSign() + { + $response = Unirest\Request::post('http://httpbin.org/post', array( + 'Accept' => 'application/json' + ), array( + 'name' => 'Mark=Hello' + )); + + $this->assertEquals(200, $response->code); + + $form = $response->body->form; + $this->assertEquals('Mark=Hello', $form->name); + } + + public function testPostArray() + { + $response = Unirest\Request::post('http://httpbin.org/post', array( + 'Accept' => 'application/json' + ), array( + 'name[0]' => 'Mark', + 'name[1]' => 'John' + )); + + $this->assertEquals(200, $response->code); + + $form = $response->body->form; + + $this->assertEquals('Mark', $form->{'name[0]'}); + $this->assertEquals('John', $form->{'name[1]'}); + } + + public function testPostWithDots() + { + $response = Unirest\Request::post('http://httpbin.org/post', array( + 'Accept' => 'application/json' + ), array( + 'user.name' => 'Mark', + 'nick' => 'thefosk' + )); + + $this->assertEquals(200, $response->code); + + $form = $response->body->form; + $this->assertEquals('Mark', $form->{'user.name'}); + $this->assertEquals('thefosk', $form->nick); + } + + public function testRawPost() + { + $response = Unirest\Request::post('http://httpbin.org/post', array( + 'Accept' => 'application/json', + 'Content-Type' => 'application/json' + ), json_encode(array( + 'author' => 'Sam Sullivan' + ))); + + $this->assertEquals(200, $response->code); + + $json = $response->body->json; + + $this->assertEquals('Sam Sullivan', $json->author); + } + + public function testPostMultidimensionalArray() + { + $response = Unirest\Request::post('http://httpbin.org/post', array( + 'Accept' => 'application/json' + ), array( + 'key' => 'value', + 'items' => array( + 'item1', + 'item2' + ) + )); + + $this->assertEquals(200, $response->code); + + $form = $response->body->form; + $this->assertEquals('value', $form->key); + $this->assertEquals('item1', $form->{'items[0]'}); + $this->assertEquals('item2', $form->{'items[1]'}); + } + + // PUT + public function testPut() + { + $response = Unirest\Request::put('http://httpbin.org/put', array( + 'Accept' => 'application/json' + ), array( + 'name' => 'Mark', + 'nick' => 'thefosk' + )); + + $this->assertEquals(200, $response->code); + + $form = $response->body->form; + $this->assertEquals('Mark', $form->name); + $this->assertEquals('thefosk', $form->nick); + } + + // PATCH + public function testPatch() + { + $response = Unirest\Request::patch('http://httpbin.org/patch', array( + 'Accept' => 'application/json' + ), array( + 'name' => 'Mark', + 'nick' => 'thefosk' + )); + + $this->assertEquals(200, $response->code); + + $form = $response->body->form; + $this->assertEquals('Mark', $form->name); + $this->assertEquals('thefosk', $form->nick); + } + + // DELETE + public function testDelete() + { + $response = Unirest\Request::delete('http://httpbin.org/delete', array( + 'Accept' => 'application/json', + 'Content-Type' => 'application/x-www-form-urlencoded' + ), array( + 'name' => 'Mark', + 'nick' => 'thefosk' + )); + + $this->assertEquals(200, $response->code); + $data = $response->body->data; + $this->assertTrue(empty($data)); + } + + // Upload + public function testUpload() + { + $response = Unirest\Request::post('http://httpbin.org/post', array( + 'Accept' => 'application/json' + ), array( + 'name' => 'Mark', + 'file' => Unirest\File::add(UPLOAD_FIXTURE) + )); + $this->assertEquals(200, $response->code); + + $files = $response->body->files; + $this->assertEquals('This is a test', $files->file); + + $form = $response->body->form; + $this->assertEquals('Mark', $form->name); + } + + public function testUploadIfFilePartOfData() + { + $response = Unirest\Request::post('http://httpbin.org/post', array( + 'Accept' => 'application/json' + ), array( + 'name' => 'Mark', + 'files[owl.gif]' => Unirest\File::add(UPLOAD_FIXTURE) + )); + $this->assertEquals(200, $response->code); + + //$files = $response->body->files; + //$this->assertEquals('This is a test', $files->file); + + $form = $response->body->form; + $this->assertEquals('Mark', $form->name); + } } From 0b29426d7f3be11f873257642e1938c02da87b27 Mon Sep 17 00:00:00 2001 From: Ahmad Nassri Date: Wed, 14 Jan 2015 19:24:20 -0500 Subject: [PATCH 33/41] adding codeclimate and updating README --- .gitignore | 1 + README.md | 37 +++++++++++++++++++++++++++++++++---- composer.json | 8 +++++--- phpunit.xml | 4 ++++ 4 files changed, 43 insertions(+), 7 deletions(-) diff --git a/.gitignore b/.gitignore index 922ede7..6db3ce1 100644 --- a/.gitignore +++ b/.gitignore @@ -1,4 +1,5 @@ .DS_Store +build vendor composer.lock composer.phar diff --git a/README.md b/README.md index 6a06281..ddb68c0 100644 --- a/README.md +++ b/README.md @@ -1,7 +1,14 @@ -# Unirest for PHP [![Build Status](https://api.travis-ci.org/Mashape/unirest-php.png)](https://travis-ci.org/Mashape/unirest-php) +# Unirest for PHP ![GitHub version][github-image] [![version][composer-image]][composer-url] + +[![Build Status][travis-image]][travis-url] +[![Code Climate][codeclimate-image]][codeclimate-url] +[![Coverage Status][codecoverage-image]][codecoverage-url] +[![Dependency Status][dependency-image]][dependency-url] Unirest is a set of lightweight HTTP libraries available in multiple languages, ideal for most applications: +## Features + * Utility methods to call `GET`, `HEAD`, `POST`, `PUT`, `DELETE`, `CONNECT`, `OPTIONS`, `TRACE`, `PATCH` requests * Supports form parameters, file uploads and custom body entities * Supports gzip @@ -18,8 +25,9 @@ Created with love by [Mashape](https://www.mashape.com) --- -### Install with Composer -If you're using [Composer](https://getcomposer.org/) to manage dependencies, you can add Unirest with it. +### Install with [Componser](https://getcomposer.org) + +If you're using Composer to manage dependencies, you can add Unirest with it. ```javascript { @@ -62,7 +70,7 @@ $response->code; // HTTP Status code $response->headers; // Headers $response->body; // Parsed body $response->raw_body; // Unparsed body -``` +```dependency-image ### File Uploads @@ -154,3 +162,24 @@ Unirest\Request::verifyPeer(false); // Disables SSL cert validation ``` By default is `true`. + +## License + +Licensed under [the MIT license](LICENSE). + +[github-image]: https://badge.fury.io/gh/mashape%2Funirest-php.svg + +[composer-url]: http://badge.fury.io/ph/mashape%2Funirest-php +[composer-image]: https://badge.fury.io/ph/mashape%2Funirest-php.svg + +[travis-url]: https://travis-ci.org/Mashape/unirest-php +[travis-image]: https://travis-ci.org/Mashape/unirest-php.png?branch=master + +[codeclimate-url]: https://codeclimate.com/github/Mashape/unirest-php +[codeclimate-image]: https://codeclimate.com/github/Mashape/unirest-php/badges/gpa.svg + +[codecoverage-url]: https://codeclimate.com/github/Mashape/unirest-php +[codecoverage-image]: https://codeclimate.com/github/Mashape/unirest-php/badges/coverage.svg + +[dependency-url]: https://www.versioneye.com/user/projects/54b702db050646ca5c00019d +[dependency-image]: https://www.versioneye.com/user/projects/54b702db050646ca5c00019d/badge.svg?style=flat diff --git a/composer.json b/composer.json index b05334e..3251532 100644 --- a/composer.json +++ b/composer.json @@ -8,11 +8,13 @@ "author": "Mashape (https://www.mashape.com)", "require": { "php": ">=5.4.0", - "ext-curl": "*", - "ext-json": "*" + "ext-curl": "0.0.0.*", + "ext-json": "~1.3" }, "require-dev": { - "phpunit/phpunit": "*" + "ext-xdebug": "~2.2", + "phpunit/phpunit": "~4.4", + "codeclimate/php-test-reporter": "0.1.*" }, "autoload": { "psr-0": { diff --git a/phpunit.xml b/phpunit.xml index fe1ce82..0966344 100644 --- a/phpunit.xml +++ b/phpunit.xml @@ -1,5 +1,9 @@ + + + + ./tests From 2a07cffe54844dd6b708d4fa952265b66b763d2e Mon Sep 17 00:00:00 2001 From: Ahmad Nassri Date: Wed, 14 Jan 2015 19:25:18 -0500 Subject: [PATCH 34/41] travis to send coverage reports --- .travis.yml | 3 +++ 1 file changed, 3 insertions(+) diff --git a/.travis.yml b/.travis.yml index 2244fa6..663e260 100644 --- a/.travis.yml +++ b/.travis.yml @@ -5,3 +5,6 @@ php: - 5.5 - 5.6 - hhvm + +after_script: + - vendor/bin/test-reporter From 9a67f24f346ffcd03ca50b01105e276afebffa74 Mon Sep 17 00:00:00 2001 From: Ahmad Nassri Date: Wed, 14 Jan 2015 19:25:37 -0500 Subject: [PATCH 35/41] removing scruitinizer --- .scrutinizer.yml | 15 --------------- 1 file changed, 15 deletions(-) delete mode 100644 .scrutinizer.yml diff --git a/.scrutinizer.yml b/.scrutinizer.yml deleted file mode 100644 index 0a46bf9..0000000 --- a/.scrutinizer.yml +++ /dev/null @@ -1,15 +0,0 @@ -tools: - php_sim: true - php_pdepend: true - php_analyzer: true - php_mess_detector: true - php_changetracking: true - sensiolabs_security_checker: true - - php_code_sniffer: - config: - standard: 'PSR2' - - php_cs_fixer: - config: - level: 'psr2' From e6f9dc1d010a39b55f6877674ff1fac2fe81e7fd Mon Sep 17 00:00:00 2001 From: Ahmad Nassri Date: Wed, 14 Jan 2015 19:38:48 -0500 Subject: [PATCH 36/41] updating README --- README.md | 80 ++++++++++++++++++++++++++++++++----------------------- 1 file changed, 47 insertions(+), 33 deletions(-) diff --git a/README.md b/README.md index ddb68c0..5295066 100644 --- a/README.md +++ b/README.md @@ -17,46 +17,58 @@ Unirest is a set of lightweight HTTP libraries available in multiple languages, * Customizable default headers for every request (DRY) * Automatic JSON parsing into a native object for JSON responses -Created with love by [Mashape](https://www.mashape.com) +## Installation ---- +### [Componser](https://getcomposer.org) -**To the community**: At this time Unirest-PHP only support syncronous requests, and I would really love to implement asynchronous support. If you guys have any feedback or ideas please comment on issue [#23](https://github.com/Mashape/unirest-php/issues/23). +To install unirest-php with Composer, just add the following to your `composer.json` file: ---- - -### Install with [Componser](https://getcomposer.org) - -If you're using Composer to manage dependencies, you can add Unirest with it. - -```javascript +```json +// composer.json { - "require" : { - "mashape/unirest-php" : "2.0.*" - }, - "autoload": { - "psr-0": {"Unirest": "src/"} - } + "require-dev": { + "mashape/unirest-php": "2.*" + } } ``` -### Install source from GitHub +or by running the following command: -Unirest-PHP requires PHP `v5.3+`. Download the PHP library from Github, and require in your script like so: - -To install the source code: - -```bash -$ git clone git@github.com:Mashape/unirest-php.git +```shell +composer require mashape/unirest-php ``` -And include it in your scripts: +This will get you the latest version of the reporter and install it. If you do want the master, untagged, version you may use the command below: -```bash +```shell +composer require mashape/php-test-reporter:@dev-master +``` + +Composer installs autoloader at `./vendor/autoloader.php`. to include the library in your script, add: + +```php +require_once 'vendor/autoload.php'; +``` + +If you use Symfony2, autoloader has to be detected automatically. + +*You can see this library on [Packagist](https://packagist.org/packages/mashape/unirest-php).* + +### Install from source + +Unirest-PHP requires PHP `v5.4+`. Download the PHP library from Github, then include `Unirest.php` in your script: + +```shell +git clone git@github.com:Mashape/unirest-php.git +``` + +```php require_once '/path/to/unirest-php/src/Unirest.php'; ``` -## Creating Request +## Usage + +### Creating a Request So you're probably wondering how using Unirest makes creating requests in PHP easier, let's look at a working example: @@ -70,7 +82,7 @@ $response->code; // HTTP Status code $response->headers; // Headers $response->body; // Parsed body $response->raw_body; // Unparsed body -```dependency-image +``` ### File Uploads @@ -101,7 +113,7 @@ Authenticating the request with basic authentication can be done by providing th $response = Unirest\Request::get("http://httpbin.org/get", null, null, "username", "password"); ``` -# Request +### Request Object ```php Unirest\Request::get($url, $headers = array(), $parameters = NULL, $username = NULL, $password = NULL) @@ -117,7 +129,7 @@ Unirest\Request::delete($url, $headers = array(), $body = NULL, $username = NULL - `username` - Basic Authentication username - `password` - Basic Authentication password -# Response +### Response Object Upon recieving a response Unirest returns the result in the form of an Object, this object should always have the same keys for each language regarding to the response details. @@ -126,11 +138,11 @@ Upon recieving a response Unirest returns the result in the form of an Object, t - `body` - Parsed response body where applicable, for example JSON responses are parsed to Objects / Associative Arrays. - `raw_body` - Un-parsed response body -# Advanced Configuration +### Advanced Configuration You can set some advanced configuration to tune Unirest-PHP: -### Timeout +#### Timeout You can set a custom timeout value (in **seconds**): @@ -138,7 +150,7 @@ You can set a custom timeout value (in **seconds**): Unirest\Request::timeout(5); // 5s timeout ``` -### Default Request Headers +#### Default Request Headers You can set default headers that will be sent on every request: @@ -153,7 +165,7 @@ You can clear the default headers anytime with: Unirest\Request::clearDefaultHeaders(); ``` -### SSL validation +#### SSL validation You can explicitly enable or disable SSL certificate validation when consuming an SSL protected endpoint: @@ -167,6 +179,8 @@ By default is `true`. Licensed under [the MIT license](LICENSE). +Created with love by [Mashape](https://www.mashape.com) + [github-image]: https://badge.fury.io/gh/mashape%2Funirest-php.svg [composer-url]: http://badge.fury.io/ph/mashape%2Funirest-php From eaaca57797d27f87649e467cd84d863b5261025f Mon Sep 17 00:00:00 2001 From: Ahmad Nassri Date: Wed, 14 Jan 2015 19:45:07 -0500 Subject: [PATCH 37/41] gitter integration --- .travis.yml | 8 ++++++++ README.md | 4 ++++ 2 files changed, 12 insertions(+) diff --git a/.travis.yml b/.travis.yml index 663e260..31212d9 100644 --- a/.travis.yml +++ b/.travis.yml @@ -8,3 +8,11 @@ php: after_script: - vendor/bin/test-reporter + +notifications: + webhooks: + urls: + - https://webhooks.gitter.im/e/802f417bb6e3e1e8b20d + on_success: always + on_failure: always + on_start: false diff --git a/README.md b/README.md index 5295066..31579ec 100644 --- a/README.md +++ b/README.md @@ -4,6 +4,7 @@ [![Code Climate][codeclimate-image]][codeclimate-url] [![Coverage Status][codecoverage-image]][codecoverage-url] [![Dependency Status][dependency-image]][dependency-url] +[![Gitter][gitter-image]][gitter-url] Unirest is a set of lightweight HTTP libraries available in multiple languages, ideal for most applications: @@ -183,6 +184,9 @@ Created with love by [Mashape](https://www.mashape.com) [github-image]: https://badge.fury.io/gh/mashape%2Funirest-php.svg +[gitter-url]: https://gitter.im/Mashape +[gitter-image]: https://badges.gitter.im/Mashape.png + [composer-url]: http://badge.fury.io/ph/mashape%2Funirest-php [composer-image]: https://badge.fury.io/ph/mashape%2Funirest-php.svg From aff17227d4f2107e26bfc041cbdeefd8625b12e9 Mon Sep 17 00:00:00 2001 From: Ahmad Nassri Date: Wed, 14 Jan 2015 19:48:14 -0500 Subject: [PATCH 38/41] typo --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 31579ec..cb7fb0d 100644 --- a/README.md +++ b/README.md @@ -20,7 +20,7 @@ Unirest is a set of lightweight HTTP libraries available in multiple languages, ## Installation -### [Componser](https://getcomposer.org) +### Using [Composer](https://getcomposer.org) To install unirest-php with Composer, just add the following to your `composer.json` file: From bcc2a3bc19186733255cbed0172299a57a8e4920 Mon Sep 17 00:00:00 2001 From: Ahmad Nassri Date: Wed, 14 Jan 2015 19:53:33 -0500 Subject: [PATCH 39/41] adding mashape logo --- README.md | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index cb7fb0d..279e830 100644 --- a/README.md +++ b/README.md @@ -180,7 +180,7 @@ By default is `true`. Licensed under [the MIT license](LICENSE). -Created with love by [Mashape](https://www.mashape.com) +Created with love by [![Mashape Logo][mashape-logo]](https://www.mashape.com/) [github-image]: https://badge.fury.io/gh/mashape%2Funirest-php.svg @@ -201,3 +201,5 @@ Created with love by [Mashape](https://www.mashape.com) [dependency-url]: https://www.versioneye.com/user/projects/54b702db050646ca5c00019d [dependency-image]: https://www.versioneye.com/user/projects/54b702db050646ca5c00019d/badge.svg?style=flat + +[mashape-logo]: https://cloud.githubusercontent.com/assets/183195/5750736/c94e178c-9c26-11e4-91b2-84bcd5d33e28.png From 1ad47092dec9195fc01c59bb58e484da17fc023b Mon Sep 17 00:00:00 2001 From: Ahmad Nassri Date: Wed, 14 Jan 2015 20:01:38 -0500 Subject: [PATCH 40/41] PHP 5.4 test --- tests/Unirest/FileTest.php | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/tests/Unirest/FileTest.php b/tests/Unirest/FileTest.php index 525f074..b7316a3 100644 --- a/tests/Unirest/FileTest.php +++ b/tests/Unirest/FileTest.php @@ -7,6 +7,11 @@ class UnirestFileTest extends \PHPUnit_Framework_TestCase public function testCURLFile() { $file = File::add(UPLOAD_FIXTURE); - $this->assertTrue($file instanceof \CURLFile); + + if (PHP_MAJOR_VERSION === 5 && PHP_MINOR_VERSION === 4) { + $this->assertEquals($file, sprintf('@%s;filename=%s;type=', UPLOAD_FIXTURE, basename(UPLOAD_FIXTURE))); + } else { + $this->assertTrue($file instanceof \CURLFile); + } } } From d188bcbd1521b6537f5401b94245e548902ef0a2 Mon Sep 17 00:00:00 2001 From: Ahmad Nassri Date: Wed, 14 Jan 2015 20:06:10 -0500 Subject: [PATCH 41/41] fix typo --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 279e830..a944682 100644 --- a/README.md +++ b/README.md @@ -87,7 +87,7 @@ $response->raw_body; // Unparsed body ### File Uploads -To upload files in a multipart form representation use the return value of `Unirest::file($path)` as the value of a parameter: +To upload files in a multipart form representation use the return value of `Unirest\File::add($path)` as the value of a parameter: ```php $headers = array("Accept" => "application/json");