Skip to content

Added cURL backup method to ApiClient #48

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Apr 18, 2016
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
42 changes: 41 additions & 1 deletion src/CodeClimate/Bundle/TestReporterBundle/ApiClient.php
Original file line number Diff line number Diff line change
Expand Up @@ -52,10 +52,50 @@ public function send($json)
if (!empty($raw_response)) {
$response = $this->buildResponse($response, $raw_response);
}
} else {
$response = $this->sendWithCurl($url, $payload);
}

return $response;
}

/**
* Send the given JSON as a request to the CodeClimate Server using cURL.
* Added as a backup if PHP Streams method fails (e.g. if allow_url_fopen is disabled).
*
* @param string $url The API end-point URL
* @param string $payload The request payload as a JSON-encoded string
* @return \stdClass Response object with (code, message, headers & body properties)
*/
private function sendWithCurl($url, $payload)
{
$response = new \stdClass;
$curl = curl_init($url);
curl_setopt($curl, CURLOPT_VERBOSE, true);
curl_setopt($curl, CURLOPT_HEADER, true);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_CONNECTTIMEOUT, 10);
curl_setopt(
$curl,
CURLOPT_HTTPHEADER,
array(
'Host: codeclimate.com',
'Content-Type: application/json',
'User-Agent: Code Climate (PHP Test Reporter v'.Version::VERSION.')',
'Content-Length: '.strlen($payload)
)
);
curl_setopt($curl, CURLOPT_CUSTOMREQUEST, 'POST');
curl_setopt($curl, CURLOPT_POSTFIELDS, $payload);
$raw_response = curl_exec($curl);

$status = curl_getinfo($curl, CURLINFO_HTTP_CODE);
if (!empty($raw_response)) {
$response = $this->buildResponse($response, $raw_response);
} else {
$error = error_get_last();
preg_match('/([0-9]{3})/', $error['message'], $match);
$errorCode = (isset($match[1])) ? $match[1] : 500;
$errorCode = (isset($match[1])) ? $match[1] : ($status ? $status : 500);

$response->code = $errorCode;
$response->message = $error['message'];
Expand Down