You are here

public function UserStatisticsManager::renderUserStatistics in Opigno statistics 3.x

Prepare the render array to display the user statistics.

Parameters

int $days: The amount of days to get stats for.

int $uid: The user ID to get stats for.

Return value

array The render array to display the user statistics.

File

src/Services/UserStatisticsManager.php, line 407

Class

UserStatisticsManager
User statistics manager service definition.

Namespace

Drupal\opigno_statistics\Services

Code

public function renderUserStatistics(int $days, int $uid = 0) : array {
  $uid = $uid ?: $this->currentUid;

  // Generate the url to update the user statistics section.
  $url = Url::fromRoute('opigno_statistics.get_user_stats_block');
  $internal = $url
    ->getInternalPath();
  $url
    ->setOption('query', [
    'token' => $this->csrfToken
      ->get($internal),
  ]);
  $url = $url
    ->toString();

  // Gather stats.
  $completed = $this
    ->getUserTrainingsNumberByStatus($days, $uid);
  $current = $this
    ->getUserTrainingsNumberByStatus($days, $uid, 'pending');
  $certificates = $this
    ->getUserCertificates($days, $uid);
  $time = $this
    ->getUserTrainingsTime($days, $uid);
  $time_progress = 2 * $time - $this
    ->getUserTrainingsTime(2 * $days, $uid);
  $formatted_time_progress = $this->dateFormatter
    ->formatInterval(abs($time_progress));

  // Calculate the progress comparing to the previous the same period.
  return [
    '#theme' => 'opigno_user_stats_block',
    '#stats' => [
      'trainings_completed' => [
        'title' => $this
          ->t('Training(s) completed'),
        'amount' => $completed,
        'progress' => 2 * $completed - $this
          ->getUserTrainingsNumberByStatus($days * 2, $uid),
      ],
      'current_trainings' => [
        'title' => $this
          ->t('Current training(s)'),
        'amount' => $current,
        'progress' => 2 * $current - $this
          ->getUserTrainingsNumberByStatus($days * 2, $uid, 'pending'),
      ],
      'certificates' => [
        'title' => $this
          ->t('Certificate(s) received'),
        'amount' => $certificates,
        'progress' => 2 * $certificates - $this
          ->getUserCertificates(2 * $days, $uid),
      ],
      'time' => [
        'title' => $this
          ->t('Time spent on Training'),
        'amount' => $this->dateFormatter
          ->formatInterval($time),
        'progress' => $time_progress < 0 ? "-{$formatted_time_progress}" : $formatted_time_progress,
      ],
    ],
    '#attached' => [
      'library' => [
        'opigno_statistics/user_statistics',
      ],
      'drupalSettings' => [
        'dashboard' => [
          'userStatsBlockUrl' => $url instanceof GeneratedUrl ? $url
            ->getGeneratedUrl() : $url,
          'userId' => $uid,
        ],
      ],
    ],
    // Don't cache data, it depends on days amount and trainings completion.
    '#cache' => [
      '#max-age' => 0,
    ],
  ];
}