You are here

function google_analytics_reports_plugin_query_google_analytics::execute in Google Analytics Reports 7.3

Executes the query and fills the associated view object with according values.

Values to set: $view->result, $view->total_rows, $view->execute_time, $view->current_page.

Overrides views_plugin_query::execute

File

plugins/google_analytics_reports_plugin_query_google_analytics.inc, line 233
Defines the default query object which builds queries for the Google Analytics Reports API.

Class

google_analytics_reports_plugin_query_google_analytics
Object used to create a Google Analytics Core Reporting API query.

Code

function execute(&$view) {

  // Initial check to see if we should attempt to run the query.
  if (!variable_get('google_analytics_reports_api_access_token', FALSE)) {

    // Optionally do not warn users on every query attempt before auth.
    if (variable_get('google_analytics_reports_warning', TRUE)) {
      drupal_set_message(t('You must <a href="@url">authorize</a> Drupal to use your Google Analytics account before you can view reports.', array(
        '@url' => url('admin/config/system/google-analytics-reports-api'),
      )), 'warning', FALSE);
    }
    return;
  }
  $query = $view->build_info['query'];
  $count_query = $view->build_info['count_query'];
  $start = microtime(TRUE);

  // Query for total number of items.
  $count_query['max_results'] = 9999;
  $count_query['start_index'] = 1;
  $count_feed = google_analytics_reports_api_report_data($count_query);

  // Process only if data is available.
  if (!empty($count_feed->results->rows)) {
    $this->pager->total_items = count($count_feed->results->rows);
    $this->pager
      ->update_page_info();

    // Adjust based on the pager's modifications to limit and offset.
    if (!empty($this->limit) || !empty($this->offset)) {
      $query['max_results'] = intval(!empty($this->limit) ? $this->limit : 1000);
      $query['start_index'] = intval(!empty($this->offset) ? $this->offset : 0) + 1;
    }
    $feed = google_analytics_reports_api_report_data($query);
    $rows = $feed->results->rows;
    foreach ($rows as $row) {
      $views_result[] = (object) $row;
    }
    $view->result = isset($views_result) ? $views_result : array();
    $view->execute_time = microtime(TRUE) - $start;
    if ($this->pager
      ->use_pager()) {
      $view->total_rows = $this->pager
        ->get_total_items();
    }

    // Add to build_info['query'] to render query in Views UI query summary
    // area.
    $view->build_info['query'] = print_r($feed->results->query, TRUE);
  }
  else {

    // Set empty query instead of current query array to prevent error
    // in Views UI.
    $view->build_info['query'] = '';

    // Display the error from Google.
    $response_data = drupal_json_decode($count_feed->response->data);
    if (isset($response_data['error']['message'])) {
      drupal_set_message(check_plain($response_data['error']['message']), 'error');
    }
  }
}