You are here

protected function MatomoBase::query in Dashboards with Layout Builder 8

Same name and namespace in other branches
  1. 2.0.x modules/dashboards_matomo/src/Plugin/Dashboard/MatomoBase.php \Drupal\dashboards_matomo\Plugin\Dashboard\MatomoBase::query()

Helper function for query matomo.

Parameters

string $action: Matomo action to call.

array $params: Parameters.

Return value

array Response array

File

modules/dashboards_matomo/src/Plugin/Dashboard/MatomoBase.php, line 176

Class

MatomoBase
Base class for matomo plugins.

Namespace

Drupal\dashboards_matomo\Plugin\Dashboard

Code

protected function query($action, array $params) : array {
  $cid = md5(serialize([
    $action,
    $params,
  ]));
  if ($data = $this
    ->getCache($cid)) {
    return $data->data;
  }
  $query = $this->matomoQuery
    ->getQuery($action);
  $query
    ->setParameters($params);
  $response = $query
    ->execute()
    ->getRawResponse();
  $response = Json::decode($response
    ->getBody()
    ->getContents());
  if (isset($response['result']) && $response['result'] == 'error') {
    throw new \Exception($response['message']);
  }
  $items = [];
  foreach ($response as $date => $values) {
    $nDates = explode(',', $date);
    array_walk($nDates, function (&$i, $key, $formatter) {
      $date = strtotime($i);
      if ($date !== FALSE) {
        $i = $formatter
          ->format($date, 'custom', 'd.m.Y');
      }
    }, \Drupal::service('date.formatter'));
    $date = implode(',', $nDates);
    if (count($nDates) > 1) {
      $date = static::formatDateRange($nDates[0], $nDates[1]);
    }
    $items[$date] = $values;
  }
  $this
    ->setCache($cid, $items, time() + 600);
  return $items;
}