You are here

abstract class MatomoBase 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

Base class for matomo plugins.

Hierarchy

Expanded class hierarchy of MatomoBase

File

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

Namespace

Drupal\dashboards_matomo\Plugin\Dashboard
View source
abstract class MatomoBase extends DashboardLazyBuildBase {
  use ChartTrait;

  /**
   * Entity query.
   *
   * @var \Drupal\matomo_reporting_api\MatomoQueryFactory
   */
  protected $matomoQuery;

  /**
   * {@inheritdoc}
   */
  public function __construct(array $configuration, $plugin_id, $plugin_definition, CacheBackendInterface $cache, MatomoQueryFactory $matomo) {
    parent::__construct($configuration, $plugin_id, $plugin_definition, $cache);
    $this->matomoQuery = $matomo;
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
    return new static($configuration, $plugin_id, $plugin_definition, $container
      ->get('dashboards.cache'), $container
      ->get('matomo.query_factory'));
  }

  /**
   * Get matomo query.
   *
   * @return \Drupal\matomo_reporting_api\MatomoQueryFactory
   *   Matomo query factory.
   */
  public function getQuery() {
    return $this->matomoQuery;
  }

  /**
   * Translate date matomo string.
   *
   * @param string $period
   *   Period to translated.
   *
   * @return string
   *   Translated date.
   */
  protected function getDateTranslated(string $period) : string {
    $format = 'Y-m-d';
    $start = time();
    $time = time();
    switch ($period) {
      case 'last_seven_days':
        $start = strtotime('-7 days');
        break;
      case 'this_week':
        $start = strtotime('monday this week');
        $time = strtotime('sunday this week');
        break;
      case 'this_month':
        $start = strtotime('first day of this month');
        $time = strtotime('last day of this month');
        break;
      case 'last_three_months':
        $start = strtotime('first day of this month -2 months');
        $time = strtotime('last day of this month');
        break;
      case 'last_six_months':
        $start = strtotime('first day of this month -5 months');
        $time = strtotime('last day of this month');
        break;
      case 'year':
        $start = strtotime('first day of this year');
        $time = strtotime('last day of this year');
        break;
      default:
        return $period;
    }
    $date = new \DateTime();
    $date
      ->setTimestamp($time);
    $startDateTime = new \DateTime();
    $startDateTime
      ->setTimestamp($start);
    return implode(',', [
      $startDateTime
        ->format($format),
      $date
        ->format($format),
    ]);
  }

  /**
   * Helper function for build rows from matomo.
   *
   * @param mixed $response
   *   Data from matomo.
   * @param string $label
   *   Label for display.
   * @param array $column
   *   Columns to show.
   */
  protected function buildDateRows($response, $label, array $column) {
    $labels = [
      $label,
    ];
    foreach ($response as $date => &$row) {
      foreach ($row as $key => $r) {
        $labels[$r['label']] = $r['label'];
        unset($row[$key]);
        $row[$r['label']] = $r;
        uksort($row, function ($a, $b) {
          return strcmp($a, $b);
        });
      }
    }
    $items = [];
    foreach ($response as $date => &$row) {
      $item = [
        $date,
      ];
      if (empty($row)) {
        if (is_array($column)) {
          foreach ($column as $c) {
            $item[] = 0;
          }
          continue;
        }
        $item[] = 0;
      }
      foreach ($row as $r) {
        if (is_array($column)) {
          foreach ($column as $c) {
            $item[] = $r[$c];
          }
          continue;
        }
        $item[] = $r[$column];
      }
      $items[] = $item;
    }
    $this
      ->setRows($items);
    $this
      ->setLabels($labels);
  }

  /**
   * Helper function for query matomo.
   *
   * @param string $action
   *   Matomo action to call.
   * @param array $params
   *   Parameters.
   *
   * @return array
   *   Response array
   */
  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;
  }

  /**
   * Helper function for short date ranges.
   *
   * @param int $d1
   *   Date start.
   * @param int $d2
   *   Date end.
   *
   * @return string
   *   Formatted date.
   */
  public static function formatDateRange($d1, $d2) {
    $d1 = new DateTime($d1);
    $d2 = new DateTime($d2);
    if ($d1
      ->format('Y-m-d') === $d2
      ->format('Y-m-d')) {
      return $d1
        ->format('d.m');
    }
    elseif ($d1
      ->format('Y-m') === $d2
      ->format('Y-m')) {
      return $d1
        ->format('d') . $d2
        ->format(' – d.m');
    }
    elseif ($d1
      ->format('Y') === $d2
      ->format('Y')) {
      return $d1
        ->format('d.m') . $d2
        ->format(' – d.m');
    }
    else {
      return $d1
        ->format('d.m.Y') . $d2
        ->format(' – d.m.Y');
    }
  }

  /**
   * {@inheritdoc}
   */
  public function buildSettingsForm(array $form, FormStateInterface $form_state, array $configuration) : array {
    $form['period'] = [
      '#type' => 'select',
      '#options' => [
        'day' => $this
          ->t('Day'),
        'week' => $this
          ->t('Week'),
        'month' => $this
          ->t('Month'),
        'year' => $this
          ->t('Year'),
      ],
      '#default_value' => isset($configuration['period']) ? $configuration['period'] : 'day',
    ];
    $form['date'] = [
      '#type' => 'select',
      '#options' => [
        'last_seven_days' => $this
          ->t('Last seven days'),
        'this_week' => $this
          ->t('This week'),
        'this_month' => $this
          ->t('This month'),
        'last_three_months' => $this
          ->t('Last 3 months'),
        'last_six_months' => $this
          ->t('Last 6 months'),
        'year' => $this
          ->t('This year'),
      ],
      '#default_value' => isset($configuration['date']) ? $configuration['date'] : 'today',
    ];
    $form['chart_type'] = [
      '#type' => 'select',
      '#options' => $this
        ->getAllowedStyles(),
      '#default_value' => isset($configuration['chart_type']) ? $configuration['chart_type'] : 'bar',
    ];
    $form['legend'] = [
      '#type' => 'checkbox',
      '#title' => $this
        ->t('Show legend'),
      '#default_value' => isset($configuration['legend']) ? $configuration['legend'] : 0,
    ];
    return $form;
  }

}

Members

Namesort descending Modifiers Type Description Overrides
ChartTrait::$empty protected property Empty flag.
ChartTrait::$labels protected property Labels.
ChartTrait::$rows protected property Rows.
ChartTrait::$type protected property Chart type.
ChartTrait::addLabel public function Add a label.
ChartTrait::addRow public function Add a row.
ChartTrait::getAllowedStyles public function Get allowed styles.
ChartTrait::renderChart public function Set all rows.
ChartTrait::setChartType public function Add a label.
ChartTrait::setEmpty public function Set this chart is empty.
ChartTrait::setLabels public function Set all labels.
ChartTrait::setRows public function Set all rows.
DashboardBase::$cache protected property Cache backend.
DashboardBase::getCache protected function Get cache for cid.
DashboardBase::massageFormValues public function Validate settings form.
DashboardBase::setCache protected function Set a new cache entry. Cache is prefixed by pluginid.
DashboardBase::validateForm public function Validate settings form. 1
DashboardLazyBuildBase::buildRenderArray public function Build render array. Overrides DashboardBase::buildRenderArray
DashboardLazyBuildBase::lazyBuildPreRender public static function Helper for lazy build render. Overrides DashboardLazyBuildInterface::lazyBuildPreRender
DashboardLazyBuildInterface::lazyBuild public static function Callback for lazy build. 6
MatomoBase::$matomoQuery protected property Entity query.
MatomoBase::buildDateRows protected function Helper function for build rows from matomo.
MatomoBase::buildSettingsForm public function Build render array. Overrides DashboardBase::buildSettingsForm 2
MatomoBase::create public static function Creates an instance of the plugin. Overrides DashboardBase::create
MatomoBase::formatDateRange public static function Helper function for short date ranges.
MatomoBase::getDateTranslated protected function Translate date matomo string.
MatomoBase::getQuery public function Get matomo query.
MatomoBase::query protected function Helper function for query matomo.
MatomoBase::__construct public function Constructs a \Drupal\Component\Plugin\PluginBase object. Overrides DashboardBase::__construct
PluginBase::$configuration protected property Configuration information passed into the plugin. 1
PluginBase::$pluginDefinition protected property The plugin implementation definition. 1
PluginBase::$pluginId protected property The plugin_id.
PluginBase::DERIVATIVE_SEPARATOR constant A string which is used to separate base plugin IDs from the derivative ID.
PluginBase::getBaseId public function Gets the base_plugin_id of the plugin instance. Overrides DerivativeInspectionInterface::getBaseId
PluginBase::getDerivativeId public function Gets the derivative_id of the plugin instance. Overrides DerivativeInspectionInterface::getDerivativeId
PluginBase::getPluginDefinition public function Gets the definition of the plugin implementation. Overrides PluginInspectionInterface::getPluginDefinition 3
PluginBase::getPluginId public function Gets the plugin_id of the plugin instance. Overrides PluginInspectionInterface::getPluginId
PluginBase::isConfigurable public function Determines if the plugin is configurable.
StringTranslationTrait::$stringTranslation protected property The string translation service. 1
StringTranslationTrait::formatPlural protected function Formats a string containing a count of items.
StringTranslationTrait::getNumberOfPlurals protected function Returns the number of plurals supported by a given language.
StringTranslationTrait::getStringTranslation protected function Gets the string translation service.
StringTranslationTrait::setStringTranslation public function Sets the string translation service to use. 2
StringTranslationTrait::t protected function Translates a string to the current language or to a given language.