You are here

public function MatomoReportsBlock::build in Matomo Reports 8

Builds and returns the renderable array for this block plugin.

If a block should not be rendered because it has no content, then this method must also ensure to return no content: it must then only return an empty array, or an empty array with #cache set (with cacheability metadata indicating the circumstances for it being empty).

Return value

array A renderable array representing the content of the block.

Overrides BlockPluginInterface::build

See also

\Drupal\block\BlockViewBuilder

File

src/Plugin/Block/MatomoReportsBlock.php, line 124

Class

MatomoReportsBlock
Provides a 'MatomoReportsBlock' block.

Namespace

Drupal\matomo_reports\Plugin\Block

Code

public function build() {
  $renderer = $this->renderer;
  $current_user = $this->currentUser;
  $build = [];
  if (!$this->moduleHandler
    ->moduleExists('matomo')) {
    $build['#markup'] = $this
      ->t('To use this block, you need to install the <a href=":url">Matomo</a> module', [
      ':url' => 'https://www.drupal.org/project/matomo',
    ]);
    return $build;
  }

  // Build the data URL with all params.
  $token_auth = MatomoData::getToken();
  $matomo_url = MatomoData::getUrl();

  // Message when no token?
  if (empty($matomo_url)) {
    $build['#markup'] = $this
      ->t('Please configure the <a href=":url">Matomo settings</a> to use this block.', [
      ':url' => '/admin/config/system/matomo',
    ]);
    return $build;
  }
  $data_params = [];
  $data_params['idSite'] = $this->configFactory
    ->get('matomo.settings')
    ->get('site_id');
  $data_params['date'] = 'today';
  $data_params['period'] = 'year';
  $data_params['module'] = 'API';
  $data_params['method'] = 'Actions.getPageUrl';
  $data_params['pageUrl'] = urldecode($_SERVER['REQUEST_URI']);
  $data_params['format'] = 'JSON';
  if (!empty($token_auth)) {
    $data_params['token_auth'] = $token_auth;
  }
  $query_string = http_build_query($data_params);
  $build['#markup'] = '<div id="matomopageviews"></div>';
  $build['#attached']['library'][] = 'matomo_reports/matomoreports';
  $build['#attached']['drupalSettings']['matomo_reports']['matomoJS']['url'] = $matomo_url;
  $build['#attached']['drupalSettings']['matomo_reports']['matomoJS']['query_string'] = $query_string;
  $build['#cache']['contexts'] = [
    'user',
    'url',
  ];
  $renderer
    ->addCacheableDependency($build, $this->entityTypeManager
    ->getStorage('user')
    ->load($current_user
    ->id()));
  return $build;
}