From 8d393488e3da0e4b33acadc308d455020d02a669 Mon Sep 17 00:00:00 2001 From: Stig Manning Date: Sat, 13 Jun 2015 23:07:59 +1000 Subject: [PATCH] Added improved error message handling for non-JSON errors from Google API Updated account data request to include easily accessible ProfileId parameter (for use with request report data method) --- example.account.php | 2 +- example.report.php | 4 ---- gapi.class.php | 27 +++++++++++++++++++++++---- 3 files changed, 24 insertions(+), 9 deletions(-) diff --git a/example.account.php b/example.account.php index 5c91cda..3aa5847 100644 --- a/example.account.php +++ b/example.account.php @@ -7,5 +7,5 @@ foreach($ga->getAccounts() as $result) { - echo $result . ' (' . $result->getId() . ")
"; + echo $result . ' ' . $result->getId() . ' (' . $result->getProfileId() . ")
"; } diff --git a/example.report.php b/example.report.php index e1ab394..c41c65e 100644 --- a/example.report.php +++ b/example.report.php @@ -38,8 +38,4 @@ Total Visits getVisits() ?> - - Results Updated - getUpdated() ?> - diff --git a/gapi.class.php b/gapi.class.php index bcde336..c704301 100644 --- a/gapi.class.php +++ b/gapi.class.php @@ -197,7 +197,7 @@ public function requestReportData($report_id, $dimensions=null, $metrics, $sort_ $parameters['max-results'] = $max_results; $parameters['prettyprint'] = gapi::dev_mode ? 'true' : 'false'; - + $url = new gapiRequest(gapi::report_data_url); $response = $url->get($parameters, $this->auth_method->generateAuthHeader()); @@ -205,7 +205,24 @@ public function requestReportData($report_id, $dimensions=null, $metrics, $sort_ if (substr($response['code'], 0, 1) == '2') { return $this->reportObjectMapper($response['body']); } else { - throw new Exception('GAPI: Failed to request report data. Error: "' . strip_tags($response['body']) . '"'); + throw new Exception('GAPI: Failed to request report data. Error: "' . $this->cleanErrorResponse($response['body']) . '"'); + } + } + + /** + * Clean error message from Google API + * + * @param String $error Error message HTML or JSON from Google API + */ + private function cleanErrorResponse($error) { + if (strpos($error, ']*>[^<]*<\/(style|title|script)>/i', '', $error); + return trim(preg_replace('/\s+/', ' ', strip_tags($error))); + } + else + { + $json = json_decode($error); + return isset($json->error->message) ? strval($json->error->message) : $error; } } @@ -245,6 +262,9 @@ protected function accountObjectMapper($json_string) { foreach ($json['items'] as $item) { foreach ($item['webProperties'] as $property) { + if (isset($property['profiles'][0]['id'])) { + $property['ProfileId'] = $property['profiles'][0]['id']; + } $results[] = new gapiAccountEntry($property); } } @@ -601,8 +621,7 @@ public function fetchToken($client_email, $key_file, $delegate_email = null) { "iat" => time(), ); - if(!empty($delegate_email)) - { + if(!empty($delegate_email)) { $claimset["sub"] = $delegate_email; }