From f618328c930ede6c132ec18bd3df6326c6c9a31b Mon Sep 17 00:00:00 2001 From: Rick Buczynski Date: Tue, 13 Jan 2015 16:02:56 -0500 Subject: [PATCH] Add headers param to API calls, auto-detect JSON for encoding to raw data, prevent exceptions caused by logging non UTF-8 data --- .../Zendesk/Zendesk/Model/Api/Abstract.php | 37 ++++++++++++++----- 1 file changed, 28 insertions(+), 9 deletions(-) diff --git a/src/app/code/community/Zendesk/Zendesk/Model/Api/Abstract.php b/src/app/code/community/Zendesk/Zendesk/Model/Api/Abstract.php index 21012f12..8861c039 100644 --- a/src/app/code/community/Zendesk/Zendesk/Model/Api/Abstract.php +++ b/src/app/code/community/Zendesk/Zendesk/Model/Api/Abstract.php @@ -24,8 +24,16 @@ protected function _getUrl($path) return $base_url . '/' . $path; } - protected function _call($endpoint, $params = null, $method = 'GET', $data = null) + protected function _call( + $endpoint, + $params = null, + $method = 'GET', + $data = null, + $headers = null + ) { + $usingRawData = false; + if($params && is_array($params) && count($params) > 0) { $args = array(); foreach($params as $arg => $val) { @@ -34,25 +42,36 @@ protected function _call($endpoint, $params = null, $method = 'GET', $data = nul $endpoint .= '?' . implode('&', $args); } + if (empty($headers)) { + $headers = array( + 'Accept' => 'application/json', + 'Content-Type' => 'application/json', + ); + } + $url = $this->_getUrl($endpoint); $method = strtoupper($method); $client = new Zend_Http_Client($url); $client->setMethod($method); - $client->setHeaders( - array( - 'Accept' => 'application/json', - 'Content-Type' => 'application/json' - ) - ); + $client->setHeaders($headers); + $client->setAuth( Mage::getStoreConfig('zendesk/general/email') . '/token', Mage::getStoreConfig('zendesk/general/password') ); if($method == 'POST' || $method == 'PUT') { - $client->setRawData(json_encode($data), 'application/json'); + $contentType = $client->getHeader('Content-Type'); + + if ($contentType == 'application/json' && !preg_match('/^[\{\[]/', $contentType)) { + $data = json_encode($data); + } + + $client->setRawData($data, $client->getHeader('Content-Type')); + + $usingRawData = true; } Mage::log( @@ -60,7 +79,7 @@ protected function _call($endpoint, $params = null, $method = 'GET', $data = nul array( 'url' => $url, 'method' => $method, - 'data' => json_encode($data), + 'data' => $usingRawData ? '' : json_encode($data), ), true ),