You are here

public function TopDownload::build in Download Count 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/TopDownload.php, line 25

Class

TopDownload
Provides a 'Top Downloaded Files' block.

Namespace

Drupal\download_count\Plugin\Block

Code

public function build() {
  $config = $this
    ->getConfiguration();
  $limit = isset($config['download_count_top_block_limit']) ? $config['download_count_top_block_limit'] : 10;
  $rows = [];
  $connection = Database::getConnection();
  $sql = $connection
    ->select('download_count_cache', 'dc');
  $sql
    ->join('file_managed', 'f', 'f.fid = dc.fid');
  $sql
    ->fields('dc', [
    'fid',
    'count',
  ]);
  $sql
    ->fields('f', [
    'filename',
    'filesize',
  ]);
  $sql
    ->orderBy('dc.count', 'DESC');
  $header = [
    [
      'data' => $this
        ->t('Name'),
      'class' => 'filename',
    ],
    [
      'data' => $this
        ->t('Size'),
      'class' => 'size',
    ],
    [
      'data' => $this
        ->t('Last Downloaded'),
      'class' => 'last',
    ],
  ];
  $result = $connection
    ->queryRange($sql, 0, $limit);
  foreach ($result as $file) {
    $row = [];
    $row[] = Html::escape($file->filename);
    $row[] = format_size($file->filesize);
    $row[] = $file->count;
    $rows[] = $row;
  }
  if (count($rows)) {
    return [
      '#theme' => 'table',
      '#header' => $header,
      '#rows' => $rows,
    ];
  }
}