You are here

public function Api::getStatsDevices in SendGrid Integration 8

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

Returns devices stats.

File

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

Class

Api
Class SendGridReportsController.

Namespace

Drupal\sendgrid_integration_reports

Code

public function getStatsDevices($subuser = '') {
  $cid = 'sendgrid_reports_devices:' . ($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 FALSE;
  }

  // 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 = 'devices/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->opens;
      }
      else {
        $data[$inneritem->name] = $inneritem->metrics->opens;
      }
    }
  }

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