Skip to content

Commit

Permalink
Add env var to write raw HTTP traffic to stderr
Browse files Browse the repository at this point in the history
It can be difficult to see the raw traffic going over the wire, but that's what
you need to write tests that integrate with the twilio-php client - the kind
you use for all of your Holodeck tests!

This isn't *exactly* what goes over the wire, but it's close enough for the
purposes of testing this library. I tried setting CURLOPT_VERBOSE first, but
that prints a bunch of debugging information in addition to the actual data.
  • Loading branch information
kevinburke committed Apr 12, 2017
1 parent cdd5b19 commit ca7c554
Showing 1 changed file with 23 additions and 1 deletion.
24 changes: 23 additions & 1 deletion Twilio/Http/CurlClient.php
Original file line number Diff line number Diff line change
Expand Up @@ -9,9 +9,11 @@
class CurlClient implements Client {
const DEFAULT_TIMEOUT = 60;
protected $curlOptions = array();
protected $debugHttp = false;

public function __construct(array $options = array()) {
$this->curlOptions = $options;
$this->debugHttp = getenv('DEBUG_HTTP_TRAFFIC') === 'true';
}

public function request($method, $url, $params = array(), $data = array(),
Expand All @@ -38,6 +40,20 @@ public function request($method, $url, $params = array(), $data = array(),
? array($parts[1], $parts[2])
: array($parts[0], $parts[1]);

if ($this->debugHttp) {
$u = parse_url($url);
$hdrLine = $method . ' ' . $u['path'];
if (isset($u['query']) && strlen($u['query']) > 0 ) {
$hdrLine = $hdrLine . '?' . $u['query'];
}
error_log($hdrLine);
foreach ($headers as $key => $value) {
error_log("$key: $value");
}
if ($method === 'POST') {
error_log("\n" . $options[CURLOPT_POSTFIELDS] . "\n");
}
}
$statusCode = curl_getinfo($curl, CURLINFO_HTTP_CODE);

$responseHeaders = array();
Expand All @@ -54,6 +70,13 @@ public function request($method, $url, $params = array(), $data = array(),
fclose($buffer);
}

if ($this->debugHttp) {
error_log("HTTP/1.1 $statusCode");
foreach ($responseHeaders as $key => $value) {
error_log("$key: $value");
}
error_log("\n$body");
}
return new Response($statusCode, $body, $responseHeaders);
} catch (\ErrorException $e) {
if (isset($curl) && is_resource($curl)) {
Expand All @@ -75,7 +98,6 @@ public function options($method, $url, $params = array(), $data = array(),
$timeout = is_null($timeout)
? self::DEFAULT_TIMEOUT
: $timeout;

$options = $this->curlOptions + array(
CURLOPT_URL => $url,
CURLOPT_HEADER => true,
Expand Down

0 comments on commit ca7c554

Please sign in to comment.