You are here

protected function DashboardForm::buildTrainingsList in Opigno statistics 8

Same name and namespace in other branches
  1. 3.x src/Form/DashboardForm.php \Drupal\opigno_statistics\Form\DashboardForm::buildTrainingsList()

Builds trainings listing.

Return value

array Render array.

1 call to DashboardForm::buildTrainingsList()
DashboardForm::buildForm in src/Form/DashboardForm.php
Form constructor.

File

src/Form/DashboardForm.php, line 306

Class

DashboardForm
Implements the statistics dashboard.

Namespace

Drupal\opigno_statistics\Form

Code

protected function buildTrainingsList($lp_ids) {
  $query = $this->database
    ->select('opigno_learning_path_achievements', 'a');
  $query
    ->addExpression('COUNT(a.completed)', 'users_completed');
  $query
    ->addExpression('AVG(a.time)', 'time');
  $query
    ->fields('a', [
    'gid',
    'name',
  ]);
  if (is_array($lp_ids)) {
    $query
      ->condition('a.gid', $lp_ids, 'IN');
  }
  $data = $query
    ->groupBy('a.gid')
    ->groupBy('a.name')
    ->orderBy('a.name')
    ->distinct()
    ->execute()
    ->fetchAll();
  $query = $this->database
    ->select('opigno_learning_path_group_user_status', 's');
  $query
    ->addField('s', 'gid');
  $query
    ->condition('s.uid', 0, '<>');
  $query
    ->addExpression('COUNT(*)', 'count');
  $query
    ->groupBy('s.gid');
  $groups = $query
    ->execute()
    ->fetchAllAssoc('gid');
  $table = [
    '#type' => 'table',
    '#attributes' => [
      'class' => [
        'statistics-table',
        'trainings-list',
        'table-striped',
      ],
    ],
    '#header' => [
      $this
        ->t('Training'),
      $this
        ->t('Nb of users'),
      $this
        ->t('Nb completed'),
      $this
        ->t('Avg time spent'),
      $this
        ->t('Details'),
    ],
    '#rows' => [],
  ];

  // Groups ids of existing groups.
  $gids = $this->database
    ->select('groups', 'g')
    ->fields('g', [
    'id',
  ])
    ->execute()
    ->fetchCol();
  foreach ($data as $row) {
    $time = max(0, round($row->time));
    $time_str = $time > 0 ? $this->date_formatter
      ->formatInterval($time) : '-';

    // Set links only for existing trainings, empty link otherwise.
    if (in_array($row->gid, $gids)) {
      $details_link = Link::createFromRoute(Markup::create('<span class="sr-only">' . t('Details @name', [
        '@name' => $row->name,
      ]) . '</span>'), 'opigno_statistics.training', [
        'group' => $row->gid,
      ])
        ->toRenderable();
      $details_link['#attributes']['class'][] = 'details';
      $details_link = [
        'data' => $details_link,
      ];
    }
    else {
      $details_link = [];
    }
    $table['#rows'][] = [
      $row->name,
      isset($groups[$row->gid]) ? $groups[$row->gid]->count : '',
      $row->users_completed,
      $time_str,
      $details_link,
    ];
  }
  return $table;
}