Skip to content

Commit 58652f9

Browse files
committed
Updated request func not to overwrite request body and created test.
1 parent cd15c07 commit 58652f9

File tree

2 files changed

+18
-5
lines changed

2 files changed

+18
-5
lines changed

lib/Tinify/Client.php

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -112,7 +112,7 @@ function request($method, $url, $body = NULL) {
112112
curl_close($request);
113113

114114
$headers = self::parseHeaders(substr($response, 0, $headerSize));
115-
$body = substr($response, $headerSize);
115+
$responseBody = substr($response, $headerSize);
116116

117117
if (isset($headers["compression-count"])) {
118118
Tinify::setCompressionCount(intval($headers["compression-count"]));
@@ -144,8 +144,8 @@ function request($method, $url, $body = NULL) {
144144

145145
if ($isJson || $isError) {
146146
/* Parse JSON bodies, always interpret errors as JSON. */
147-
$body = json_decode($body);
148-
if (!$body) {
147+
$responseBody = json_decode($responseBody);
148+
if (!$responseBody) {
149149
$message = sprintf("Error while parsing response: %s (#%d)",
150150
PHP_VERSION_ID >= 50500 ? json_last_error_msg() : "Error",
151151
json_last_error());
@@ -160,11 +160,11 @@ function request($method, $url, $body = NULL) {
160160
if ($status == 404) {
161161
throw Exception::create(null, null, $status);
162162
} else {
163-
throw Exception::create($body->message, $body->error, $status);
163+
throw Exception::create($responseBody->message, $responseBody->error, $status);
164164
}
165165
}
166166

167-
return (object) array("body" => $body, "headers" => $headers);
167+
return (object) array("body" => $responseBody, "headers" => $headers);
168168
} else {
169169
$message = sprintf("%s (#%d)", curl_error($request), curl_errno($request));
170170
curl_close($request);

test/TinifyClientTest.php

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -231,6 +231,19 @@ public function testRequestWithServerErrorRepeatedlyShouldThrowServerException()
231231
$client->request("get", "/");
232232
}
233233

234+
public function testRequestWithBodyAndServerErrorRepeatedlyShouldThrowServerException() {
235+
CurlMock::register("https://api.tinify.com/", array(
236+
"body" => '{"email":"[email protected]"}'
237+
), array(
238+
"status" => 500, "body" => '{"error":"InternalServerError","message":"Oops!"}'
239+
));
240+
241+
$this->setExpectedException("Tinify\ServerException");
242+
$client = new Tinify\Client("key");
243+
$response = $client->request("post", "/", array("email"=> "[email protected]"));
244+
$this->assertEquals("", $response->body);
245+
}
246+
234247
public function testRequestWithServerErrorRepeatedlyShouldThrowExceptionWithMessage() {
235248
CurlMock::register("https://api.tinify.com/", array(
236249
"status" => 584, "body" => '{"error":"InternalServerError","message":"Oops!"}'

0 commit comments

Comments
 (0)