Skip to content

Commit

Permalink
Added improved error message handling for non-JSON errors from Google…
Browse files Browse the repository at this point in the history
… API

Updated account data request to include easily accessible ProfileId parameter (for use with request report data method)
  • Loading branch information
erebusnz committed Jun 13, 2015
1 parent 075fc52 commit 8d39348
Show file tree
Hide file tree
Showing 3 changed files with 24 additions and 9 deletions.
2 changes: 1 addition & 1 deletion example.account.php
Expand Up @@ -7,5 +7,5 @@

foreach($ga->getAccounts() as $result)
{
echo $result . ' (' . $result->getId() . ")<br />";
echo $result . ' ' . $result->getId() . ' (' . $result->getProfileId() . ")<br />";
}
4 changes: 0 additions & 4 deletions example.report.php
Expand Up @@ -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>
27 changes: 23 additions & 4 deletions gapi.class.php
Expand Up @@ -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;
}
}

Expand Down Expand Up @@ -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);
}
}
Expand Down Expand Up @@ -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;
}

Expand Down

0 comments on commit 8d39348

Please sign in to comment.