You are here

public function Api::getStatsBrowser in SendGrid Integration 8.2

Same name and namespace in other branches
  1. 8 modules/sendgrid_integration_reports/src/Api.php \Drupal\sendgrid_integration_reports\Api::getStatsBrowser()

Returns browser stats.

File

modules/sendgrid_integration_reports/src/Api.php, line 270

Class

Api
Class SendGridReportsController.

Namespace

Drupal\sendgrid_integration_reports

Code

public function getStatsBrowser($subuser = '') {
  $cid = 'sendgrid_reports_browsers:' . ($subuser ? $subuser : 'global');
  if ($cache = $this->cacheFactory
    ->get($this->bin)
    ->get($cid)) {
    return $cache->data;
  }

  // Load key from variables and throw errors if not there.
  if (empty($this->apiKey)) {
    return [];
  }

  // Set start date and end date for global stats - default 30 days back.
  $start_date = empty($config['start_date']) ? date('Y-m-d', strtotime('today - 30 days')) : $config['start_date'];
  $end_date = empty($config['end_date']) ? date('Y-m-d', strtotime('today')) : $config['end_date'];

  // Set aggregation of stats - default day.
  $aggregated_by = isset($config['aggregated_by']) ? $config['aggregated_by'] : 'day';
  $path = 'browsers/stats';
  $query = [
    'start_date' => $start_date,
    'end_date' => $end_date,
    'aggregated_by' => $aggregated_by,
  ];

  // Lets try and retrieve the browser statistics.
  $statsdata = $this
    ->getResponse($path, $query);
  if (!$stats_data) {
    return [];
  }
  $data = [];

  // Determine all browsers. Nested foreach to
  // iterate over all data returned per aggregation.
  foreach ($statsdata as $item) {
    foreach ($item->stats as $inneritem) {
      if (array_key_exists($inneritem->name, $data)) {
        $data[$inneritem->name] += $inneritem->metrics->clicks;
      }
      else {
        $data[$inneritem->name] = $inneritem->metrics->clicks;
      }
    }
  }

  // Save data to cache.
  $this
    ->setCache($cid, $data);
  return $data;
}