From 360c179b5117380288d0db0496ab0f4706f3b28e Mon Sep 17 00:00:00 2001 From: Rodrigo Polo Date: Sat, 25 Jul 2020 16:32:04 -0600 Subject: [PATCH] Added headers methods, and RAW data var --- src/Twitter.php | 36 +++++++++++++++++++++++++++++++++++- 1 file changed, 35 insertions(+), 1 deletion(-) diff --git a/src/Twitter.php b/src/Twitter.php index 952e568..1b51a1f 100644 --- a/src/Twitter.php +++ b/src/Twitter.php @@ -43,6 +43,12 @@ class Twitter CURLOPT_USERAGENT => 'Twitter for PHP', ]; + /** @var array */ + public $headers; + + /** @var string */ + public $body; + /** @var OAuth\Consumer */ private $consumer; @@ -312,9 +318,11 @@ public function request(string $resource, string $method, array $data = [], arra $request->sign_request(new OAuth\SignatureMethod_HMAC_SHA1, $this->consumer, $this->token); $headers[] = $request->to_header(); + $this->headers = []; // Header array cleanup + $options = [ CURLOPT_URL => $resource, - CURLOPT_HEADER => false, + CURLOPT_HEADERFUNCTION => [$this, '_setHeader'], CURLOPT_RETURNTRANSFER => true, CURLOPT_HTTPHEADER => $headers, ] + $this->httpOptions; @@ -338,6 +346,8 @@ public function request(string $resource, string $method, array $data = [], arra throw new Exception('Server error: ' . curl_error($curl)); } + $this->body = $result; // RAW body + if (strpos(curl_getinfo($curl, CURLINFO_CONTENT_TYPE), 'application/json') !== false) { $payload = @json_decode($result, false, 128, JSON_BIGINT_AS_STRING); // intentionally @ if ($payload === false) { @@ -432,6 +442,30 @@ public static function clickable(stdClass $status): string } return $s; } + + + /** + * Saves headers to the instance + */ + private function _setHeader($ch, $header) + { + $this->headers[] = trim($header); + return strlen($header); + } + + /** + * Get headers in an indexed array + */ + public function getHeaderArray() + { + $headers_array = []; + foreach ($this->headers as $h) { + if(preg_match_all('/^([A-Za-z-]+)\: ([ -~]+)/', $h, $matches, PREG_SET_ORDER, 0)){ + $headers_array[$matches[0][1]] = $matches[0][2]; + } + } + return $headers_array; + } }