Permalink
Browse files

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)
  • Loading branch information...
1 parent 075fc52 commit 8d393488e3da0e4b33acadc308d455020d02a669 @erebusnz committed Jun 13, 2015
Showing with 24 additions and 9 deletions.
  1. +1 −1 example.account.php
  2. +0 −4 example.report.php
  3. +23 −4 gapi.class.php
View
@@ -7,5 +7,5 @@
foreach($ga->getAccounts() as $result)
{
- echo $result . ' (' . $result->getId() . ")<br />";
+ echo $result . ' ' . $result->getId() . ' (' . $result->getProfileId() . ")<br />";
}
View
@@ -38,8 +38,4 @@
<th>Total Visits</th>
<td><?php echo $ga->getVisits() ?></td>
</tr>
-<tr>
- <th>Results Updated</th>
- <td><?php echo $ga->getUpdated() ?></td>
-</tr>
</table>
View
@@ -197,15 +197,32 @@ 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());
//HTTP 2xx
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, '<html') !== false) {
+ $error = preg_replace('/<(style|title|script)[^>]*>[^<]*<\/(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;
}

0 comments on commit 8d39348

Please sign in to comment.