View source
<?php
class RestfulCurlBaseTestCase extends DrupalWebTestCase {
protected function httpRequest($url, $method = \RestfulInterface::GET, $body = NULL, $headers = array(), $use_token = TRUE) {
$format = 'json';
switch ($method) {
case \RestfulInterface::GET:
$options = isset($body) ? array(
'absolute' => TRUE,
'query' => $body,
) : array(
'absolute' => TRUE,
);
$curl_options = array(
CURLOPT_HTTPGET => TRUE,
CURLOPT_URL => url($url, $options),
CURLOPT_NOBODY => FALSE,
);
break;
case \RestfulInterface::HEAD:
$options = isset($body) ? array(
'absolute' => TRUE,
'query' => $body,
) : array(
'absolute' => TRUE,
);
$curl_options = array(
CURLOPT_HTTPGET => FALSE,
CURLOPT_CUSTOMREQUEST => \RestfulInterface::HEAD,
CURLOPT_URL => url($url, $options),
CURLOPT_NOBODY => FALSE,
);
break;
case \RestfulInterface::POST:
$curl_options = array(
CURLOPT_HTTPGET => FALSE,
CURLOPT_POST => TRUE,
CURLOPT_POSTFIELDS => $body,
CURLOPT_URL => url($url, array(
'absolute' => TRUE,
)),
CURLOPT_NOBODY => FALSE,
);
if (empty($headers['Content-Type'])) {
$headers['Content-Type'] = 'application/' . $format;
$curl_options[CURLOPT_POSTFIELDS] = http_build_query($body);
}
break;
case \RestfulInterface::PUT:
case \RestfulInterface::PATCH:
$curl_options = array(
CURLOPT_HTTPGET => FALSE,
CURLOPT_CUSTOMREQUEST => $method,
CURLOPT_POSTFIELDS => $body,
CURLOPT_URL => url($url, array(
'absolute' => TRUE,
)),
CURLOPT_NOBODY => FALSE,
);
if (empty($headers['Content-Type'])) {
$headers['Content-Type'] = 'application/' . $format;
$curl_options[CURLOPT_POSTFIELDS] = http_build_query($body);
}
break;
case \RestfulInterface::DELETE:
$curl_options = array(
CURLOPT_HTTPGET => FALSE,
CURLOPT_CUSTOMREQUEST => \RestfulInterface::DELETE,
CURLOPT_URL => url($url, array(
'absolute' => TRUE,
)),
CURLOPT_NOBODY => FALSE,
);
break;
}
$curl_options += array(
CURLOPT_HTTPHEADER => array(),
);
if ($this->loggedInUser && \RestfulBase::isWriteMethod($method, FALSE) && $use_token) {
if (empty($this->csrfToken)) {
$response = $this
->drupalGet('api/session/token');
$result = drupal_json_decode($response);
$this->csrfToken = $result['X-CSRF-Token'];
}
$headers['X-CSRF-Token'] = $this->csrfToken;
}
foreach ($headers as $key => $value) {
$curl_options[CURLOPT_HTTPHEADER][] = $key . ': ' . $value;
}
$response = $this
->curlExec($curl_options);
$response_headers = $this
->drupalGetHeaders();
$response_headers = implode("\n", $response_headers);
$code = curl_getinfo($this->curlHandle, CURLINFO_HTTP_CODE);
$this
->verbose($method . ' request to: ' . $url . '<hr />Code: ' . $code . '<hr />Response headers: ' . $response_headers . '<hr />Response body: ' . $response);
return array(
'code' => $code,
'headers' => $response_headers,
'body' => $response,
);
}
}