View source
<?php
namespace Drupal\opigno_learning_path\Entity;
use Drupal\Component\Plugin\Exception\InvalidPluginDefinitionException;
use Drupal\Component\Plugin\Exception\PluginException;
use Drupal\Component\Plugin\Exception\PluginNotFoundException;
use Drupal\Core\Field\BaseFieldDefinition;
use Drupal\Core\Entity\ContentEntityBase;
use Drupal\Core\Entity\EntityTypeInterface;
use Drupal\Core\Field\FieldDefinitionInterface;
use Drupal\Core\Session\AccountInterface;
use Drupal\group\Entity\Group;
use Drupal\group\Entity\GroupInterface;
use Drupal\opigno_learning_path\LPStatusInterface;
class LPStatus extends ContentEntityBase implements LPStatusInterface {
protected $userAttempts = [];
protected $userActiveAttempt = [];
public function getTrainingId() {
return $this
->get('gid')->target_id;
}
public function setTrainingId($id) {
$this
->set('gid', $id);
return $this;
}
public function getTraining() {
return $this
->get('gid')->entity;
}
public function setTraining($training) {
$this
->set('gid', $training
->id());
return $this;
}
public function getUserId() {
return $this
->get('uid')->target_id;
}
public function setUserId($uid) {
$this
->set('uid', $uid);
return $this;
}
public function getUser() {
return $this
->get('uid')->entity;
}
public function setUser(AccountInterface $account) {
$this
->set('uid', $account
->id());
return $this;
}
public function getStatus() {
$value = $this
->get('status')
->getValue();
if (empty($value)) {
return NULL;
}
return $value[0]['value'];
}
public function setStatus($status) {
$this
->set('status', $status);
return $this;
}
public function getScore() {
return $this
->get('score')->value;
}
public function setScore($value) {
$this
->set('score', $value);
return $this;
}
public function getFinished() {
$value = $this
->get('finished')
->getValue();
if (empty($value)) {
return NULL;
}
return $value[0]['value'];
}
public function setFinished($timestamp) {
$this
->set('finished', $timestamp);
return $this;
}
public function isFinished() {
return (bool) $this->finished->value != 0;
}
public function getStarted() {
$value = $this
->get('started')
->getValue();
if (empty($value)) {
return NULL;
}
return $value[0]['value'];
}
public function setStarted($timestamp) {
$this
->set('started', $timestamp);
return $this;
}
public function isStarted() {
return (bool) $this->started->value != 0;
}
public static function getTrainingStatus($gid, $uid, $type = 'best') {
$db_connection = \Drupal::service('database');
try {
$result = $db_connection
->select('user_lp_status', 'lp')
->fields('lp')
->condition('gid', $gid)
->condition('uid', $uid)
->orderBy('finished', 'DESC')
->execute()
->fetchCol();
} catch (\Exception $e) {
\Drupal::logger('opigno_learning_path')
->error($e
->getMessage());
\Drupal::messenger()
->addMessage($e
->getMessage(), 'error');
}
return array_shift($result);
}
public static function isCertificateExpireSet(Group $group) : bool {
return (bool) $group
->get('field_certificate_expire')
->getString();
}
public static function getCertificateExpirationPeriod(Group $group) {
$value = $group
->get('field_certificate_expire_results')
->getValue();
if (empty($value)) {
return NULL;
}
return (int) $value[0]['value'];
}
public static function getLatestCertificateTimestamp($gid, $uid) {
$db_connection = \Drupal::service('database');
$result = $db_connection
->select('user_lp_status_expire', 'lps')
->fields('lps', [
'latest_cert_date',
])
->condition('gid', $gid)
->condition('uid', $uid)
->execute()
->fetchField();
if ($result) {
return $result;
}
return NULL;
}
public static function getCertificateExpireTimestamp($gid, $uid) : ?int {
$group = Group::load($gid);
try {
$completed_on = opigno_learning_path_completed_on($gid, $uid, TRUE);
} catch (InvalidPluginDefinitionException|PluginNotFoundException|PluginException $e) {
$completed_on = NULL;
watchdog_exception('opigno_learning_path_exception', $e);
}
if (!$completed_on || !$group instanceof GroupInterface) {
return \Drupal::database()
->select('user_lp_status_expire', 'lps')
->fields('lps', [
'expire',
])
->condition('gid', $gid)
->condition('uid', $uid)
->execute()
->fetchField();
}
if (!self::isCertificateExpireSet($group)) {
return NULL;
}
$field = 'field_certificate_expire_results';
$definitions = \Drupal::service('entity_field.manager')
->getFieldDefinitions('group', 'learning_path');
$definition = $definitions[$field] ?? NULL;
if (!$definition instanceof FieldDefinitionInterface) {
return NULL;
}
$options = $definition
->getSetting('allowed_values');
$valid_for = $group
->get($field)
->getString();
$valid_for = $options[$valid_for] ?? $valid_for . ' months';
return strtotime($valid_for, $completed_on) ?? NULL;
}
public static function setCertificateExpireTimestamp($gid, $uid, $latest_cert_date = 0, $expire = 0) {
$db_connection = \Drupal::service('database');
try {
$result = $db_connection
->select('user_lp_status_expire', 'lps')
->fields('lps', [
'id',
])
->condition('gid', $gid)
->condition('uid', $uid)
->execute()
->fetchField();
if (!$result) {
$db_connection
->insert('user_lp_status_expire')
->fields([
'gid' => $gid,
'uid' => $uid,
'latest_cert_date' => $latest_cert_date,
'expire' => $expire,
])
->execute();
}
if ($result) {
$db_connection
->merge('user_lp_status_expire')
->key([
'gid' => $gid,
'uid' => $uid,
])
->fields([
'gid' => $gid,
'uid' => $uid,
'latest_cert_date' => $latest_cert_date,
'expire' => $expire,
])
->execute();
}
} catch (\Exception $e) {
\Drupal::logger('opigno_learning_path')
->error($e
->getMessage());
\Drupal::messenger()
->addMessage($e
->getMessage(), 'error');
}
}
public static function isCertificateExpired(Group $group, $uid) : bool {
$expiration = self::getCertificateExpireTimestamp((int) $group
->id(), $uid);
return $expiration && $expiration < time();
}
public static function removeCertificateExpiration($gid, $uid = NULL) {
$db_connection = \Drupal::service('database');
try {
$query = $db_connection
->delete('user_lp_status_expire');
$query
->condition('gid', $gid);
if ($uid) {
$query
->condition('uid', $uid);
}
$query
->execute();
} catch (\Exception $e) {
\Drupal::logger('opigno_learning_path')
->error($e
->getMessage());
\Drupal::messenger()
->addMessage($e
->getMessage(), 'error');
}
}
public static function getTrainingStartDate(Group $group, $uid) {
$start_date = NULL;
$expiration_set = LPStatus::isCertificateExpireSet($group);
if ($expiration_set) {
$gid = $group
->id();
if ($expire_timestamp = LPStatus::getCertificateExpireTimestamp($gid, $uid)) {
if (time() >= $expire_timestamp) {
$start_date = $expire_timestamp;
}
else {
if ($existing_cert_date = LPStatus::getLatestCertificateTimestamp($gid, $uid)) {
$start_date = $existing_cert_date;
}
}
}
}
return $start_date;
}
public static function setUserNotification($gid, $uid, $value) {
$db_connection = \Drupal::service('database');
try {
$db_connection
->merge('user_lp_status_expire')
->key([
'gid' => $gid,
'uid' => $uid,
])
->fields([
'notified' => $value,
])
->execute();
} catch (\Exception $e) {
\Drupal::logger('opigno_learning_path')
->error($e
->getMessage());
\Drupal::messenger()
->addMessage($e
->getMessage(), 'error');
}
}
public static function getCertificateExpirationMessage($gid, $uid, $type = NULL) {
$expire_text = '';
if (!empty($type)) {
switch ($type) {
case 'valid':
$expire_text = t('Valid until') . ' ';
break;
case 'expired':
$expire_text = t('Expired on') . ' ';
break;
}
}
$date_formatter = \Drupal::service('date.formatter');
$expire = LPStatus::getCertificateExpireTimestamp($gid, $uid);
return !empty($expire) ? $expire_text . $date_formatter
->format($expire, 'custom', 'F d, Y') : '';
}
public static function baseFieldDefinitions(EntityTypeInterface $entity_type) {
$fields['id'] = BaseFieldDefinition::create('integer')
->setLabel(t('ID'))
->setDescription(t('The ID of the Term entity.'))
->setReadOnly(TRUE);
$fields['uuid'] = BaseFieldDefinition::create('uuid')
->setLabel(t('UUID'))
->setDescription(t('The UUID of the training status.'))
->setReadOnly(TRUE);
$fields['uid'] = BaseFieldDefinition::create('entity_reference')
->setLabel(t('User'))
->setDescription(t('The user ID of the LP Status entity.'))
->setSetting('target_type', 'user')
->setSetting('handler', 'default');
$fields['gid'] = BaseFieldDefinition::create('entity_reference')
->setLabel(t('Training'))
->setDescription(t('The Training of the LP Status entity.'))
->setSettings([
'target_type' => 'group',
'default_value' => 0,
]);
$fields['score'] = BaseFieldDefinition::create('integer')
->setLabel(t('Score'))
->setDescription(t('The score the user obtained for the training.'));
$fields['status'] = BaseFieldDefinition::create('string')
->setLabel(t('Status'))
->setDescription(t('The training status - passed/failed.'))
->setSettings([
'max_length' => 15,
])
->setDefaultValue('');
$fields['started'] = BaseFieldDefinition::create('created')
->setLabel(t('Started'))
->setDescription(t('The time that the training has started.'))
->setDefaultValue(0);
$fields['finished'] = BaseFieldDefinition::create('timestamp')
->setLabel(t('Finished'))
->setDescription(t('The time that the training finished.'))
->setDefaultValue(0);
return $fields;
}
}