You are here

function Reports::geo_chart in Yandex.Metrics 8.2

The function generates pie chart with geographical information on visitors.

File

yandex_metrics_reports/src/Reports.php, line 152
Contains \Drupal\yandex_metrics_reports\YandexMetricsReports.

Class

Reports
Reports manager for YandexMetrics module.

Namespace

Drupal\yandex_metrics_reports

Code

function geo_chart() {
  $date_range = _yandex_metrics_reports_filter_to_date_range($this->filter);
  $parameters = array(
    'id' => $this->counter_id,
    'date1' => $date_range['start_date'],
    'date2' => $date_range['end_date'],
  );
  $results = yandex_metrics_reports_retreive_data('/stat/geo', $parameters);
  $geo = json_decode($results
    ->getBody(TRUE));
  if (empty($geo->data)) {
    return t('There is no information about geography of visits for the selected date range.');
  }
  $total_visits = $geo->totals->visits;

  // Exclude unknown visits.
  foreach ($geo->data as $key => $value) {
    if ($value->name == "Не определено") {
      $total_visits -= $value->visits;
      unset($geo->data[$key]);
      break;
    }
  }
  $i = 1;
  $sum_visits = 0;
  foreach ($geo->data as $value) {
    $visits = (int) $value->visits;
    if ($i > 10) {
      $others_visits = $total_visits - $sum_visits;
      $data[] = array(
        'legends' => t('Others') . ' (' . round($others_visits * 100 / $total_visits, 1) . '%' . ')',
        'visits' => $others_visits,
      );
      break;
    }
    $sum_visits += $visits;
    $name = String::checkPlain($value->name);
    $data[] = array(
      'legends' => $i . '. ' . $name . ' (' . round($visits * 100 / $total_visits, 1) . '%' . ')',
      'visits' => $visits,
    );
    $i++;
  }
  $chart = array(
    '#theme' => 'visualization',
    '#options' => array(
      'title' => t('Geography of Visits'),
      'width' => 500,
      'height' => 230,
      'fields' => array(
        'legends' => array(
          'label' => 'legends',
          'enabled' => TRUE,
        ),
        'visits' => array(
          'label' => 'visits',
          'enabled' => TRUE,
        ),
      ),
      'xAxis' => array(
        'labelField' => 'legends',
      ),
      'data' => $data,
      'type' => 'pie',
    ),
  );
  return drupal_render($chart);
}