StatisticsCommands.php in Opigno statistics 3.x
File
src/Commands/StatisticsCommands.php
View source
<?php
namespace Drupal\opigno_statistics\Commands;
use Drupal\group\Entity\Group;
use Drush\Commands\DrushCommands;
class StatisticsCommands extends DrushCommands {
public function updateStatistics($uid = NULL, $gid = NULL) {
if ($uid && !$gid || !$uid && $gid) {
$this
->output()
->writeln('Should be two params - user ID and a training ID.');
return 2;
}
$achievements_table = 'opigno_learning_path_achievements';
$achievements_steps_table = 'opigno_learning_path_step_achievements';
$db_connection = \Drupal::service('database');
if ($gid) {
$ids = [
$gid,
];
}
else {
$ids = $db_connection
->select('groups_field_data', 'g')
->fields('g', [
'id',
])
->condition('type', 'learning_path')
->execute()
->fetchCol();
}
if ($ids) {
$groups = Group::loadMultiple($ids);
if ($groups) {
if ($uid && $gid) {
$db_connection
->delete($achievements_table)
->condition('uid', $uid)
->condition('gid', $gid)
->execute();
$db_connection
->delete($achievements_steps_table)
->condition('uid', $uid)
->condition('gid', $gid)
->execute();
}
else {
$db_connection
->truncate($achievements_table)
->execute();
$db_connection
->truncate($achievements_steps_table)
->execute();
}
foreach ($groups as $group) {
$gid = $group
->id();
$this
->output()
->writeln('Group (' . $gid . ') - "' . $group
->label() . '"');
if ($members = $group
->getMembers()) {
foreach ($members as $group_membership) {
$user = $group_membership
->getUser();
$member_uid = $user
->id();
if ($uid && $uid != $member_uid) {
continue;
}
$this
->output()
->writeln(' - user (' . $member_uid . ') - "' . $user
->getDisplayName() . '"');
try {
opigno_learning_path_save_achievements($gid, $member_uid);
} catch (\Exception $e) {
\Drupal::logger('opigno_statistics')
->error($e
->getMessage());
\Drupal::messenger()
->addMessage($e
->getMessage(), 'error');
}
if ($steps = opigno_learning_path_get_all_steps($gid, $member_uid)) {
foreach ($steps as $step) {
try {
$parent_id = isset($current_step['parent']) ? opigno_learning_path_save_step_achievements($gid, $member_uid, $step['parent']) : 0;
opigno_learning_path_save_step_achievements($gid, $member_uid, $step, $parent_id);
} catch (\Exception $e) {
\Drupal::logger('opigno_statistics')
->error($e
->getMessage());
\Drupal::messenger()
->addMessage($e
->getMessage(), 'error');
}
}
}
}
}
}
}
}
}
}