Skip to content

Commit a8226e7

Browse files
committedApr 18, 2016
Merge pull request #48 from aensley/master
Added cURL backup method to ApiClient
2 parents a026a4b + 7e720a4 commit a8226e7

File tree

1 file changed

+41
-1
lines changed

1 file changed

+41
-1
lines changed
 

‎src/CodeClimate/Bundle/TestReporterBundle/ApiClient.php

+41-1
Original file line numberDiff line numberDiff line change
@@ -52,10 +52,50 @@ public function send($json)
5252
if (!empty($raw_response)) {
5353
$response = $this->buildResponse($response, $raw_response);
5454
}
55+
} else {
56+
$response = $this->sendWithCurl($url, $payload);
57+
}
58+
59+
return $response;
60+
}
61+
62+
/**
63+
* Send the given JSON as a request to the CodeClimate Server using cURL.
64+
* Added as a backup if PHP Streams method fails (e.g. if allow_url_fopen is disabled).
65+
*
66+
* @param string $url The API end-point URL
67+
* @param string $payload The request payload as a JSON-encoded string
68+
* @return \stdClass Response object with (code, message, headers & body properties)
69+
*/
70+
private function sendWithCurl($url, $payload)
71+
{
72+
$response = new \stdClass;
73+
$curl = curl_init($url);
74+
curl_setopt($curl, CURLOPT_VERBOSE, true);
75+
curl_setopt($curl, CURLOPT_HEADER, true);
76+
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
77+
curl_setopt($curl, CURLOPT_CONNECTTIMEOUT, 10);
78+
curl_setopt(
79+
$curl,
80+
CURLOPT_HTTPHEADER,
81+
array(
82+
'Host: codeclimate.com',
83+
'Content-Type: application/json',
84+
'User-Agent: Code Climate (PHP Test Reporter v'.Version::VERSION.')',
85+
'Content-Length: '.strlen($payload)
86+
)
87+
);
88+
curl_setopt($curl, CURLOPT_CUSTOMREQUEST, 'POST');
89+
curl_setopt($curl, CURLOPT_POSTFIELDS, $payload);
90+
$raw_response = curl_exec($curl);
91+
92+
$status = curl_getinfo($curl, CURLINFO_HTTP_CODE);
93+
if (!empty($raw_response)) {
94+
$response = $this->buildResponse($response, $raw_response);
5595
} else {
5696
$error = error_get_last();
5797
preg_match('/([0-9]{3})/', $error['message'], $match);
58-
$errorCode = (isset($match[1])) ? $match[1] : 500;
98+
$errorCode = (isset($match[1])) ? $match[1] : ($status ? $status : 500);
5999

60100
$response->code = $errorCode;
61101
$response->message = $error['message'];

0 commit comments

Comments
 (0)
Please sign in to comment.