public function request($resource, $method, array $data = NULL, array $files = NULL)
{
if (!strpos($resource, '://')) {
if (!strpos($resource, '.')) {
$resource .= '.json';
}
$resource = self::API_URL . $resource;
}
$hasCURLFile = class_exists('CURLFile', FALSE) && defined('CURLOPT_SAFE_UPLOAD');
foreach ((array) $data as $key => $val) {
if ($val === NULL) {
unset($data[$key]);
} elseif ($files && !$hasCURLFile && substr($val, 0, 1) === '@') {
throw new TwitterException('Due to limitation of cURL it is not possible to send message starting with @ and upload file at the same time in PHP < 5.5');
}
}
foreach ((array) $files as $key => $file) {
if (!is_file($file)) {
throw new TwitterException("Cannot read the file {$file}. Check if file exists on disk and check its permissions.");
}
$data[$key] = $hasCURLFile ? new CURLFile($file) : '@' . $file;
}
$request = Twitter_OAuthRequest::from_consumer_and_token($this->consumer, $this->token, $method, $resource, $files ? [] : $data);
$request->sign_request(new Twitter_OAuthSignatureMethod_HMAC_SHA1(), $this->consumer, $this->token);
$options = [CURLOPT_HEADER => FALSE, CURLOPT_RETURNTRANSFER => TRUE] + ($method === 'POST' ? [CURLOPT_POST => TRUE, CURLOPT_POSTFIELDS => $files ? $data : $request->to_postdata(), CURLOPT_URL => $files ? $request->to_url() : $request->get_normalized_http_url()] : [CURLOPT_URL => $request->to_url()]) + $this->httpOptions;
if ($method === 'POST' && $hasCURLFile) {
$options[CURLOPT_SAFE_UPLOAD] = TRUE;
}
$curl = curl_init();
curl_setopt_array($curl, $options);
$result = curl_exec($curl);
if (curl_errno($curl)) {
throw new TwitterException('Server error: ' . curl_error($curl));
}
$payload = defined('JSON_BIGINT_AS_STRING') ? @json_decode($result, FALSE, 128, JSON_BIGINT_AS_STRING) : @json_decode($result);
// intentionally @
if ($payload === FALSE) {
throw new TwitterException('Invalid server response');
}
$code = curl_getinfo($curl, CURLINFO_HTTP_CODE);
if ($code >= 400) {
throw new TwitterException(isset($payload->errors[0]->message) ? $payload->errors[0]->message : "Server error #{$code} with answer {$result}", $code);
}
return $payload;
}