You are here

function opigno_learning_path_entity_insert in Opigno Learning path 8

Same name and namespace in other branches
  1. 3.x opigno_learning_path.module \opigno_learning_path_entity_insert()

Implements hook_entity_insert().

File

./opigno_learning_path.module, line 2451
Contains opigno_learning_path.module.

Code

function opigno_learning_path_entity_insert(EntityInterface $entity) {
  if ($entity
    ->bundle() == 'opigno_class-group_membership') {

    // Get class group id.
    $gid = $entity
      ->getGroup()
      ->id();
    if (!empty($gid) && is_numeric($gid)) {
      try {

        // Get class parent groups.
        $parent_groups = LearningPathContent::getClassGroups($gid);
        if ($parent_groups) {
          foreach ($parent_groups as $parent) {
            $group = Group::load($parent->gid);
            $user = $entity
              ->getEntity();
            if ($group && $user) {

              // Check if user is not a member.
              if ($group
                ->getMember($user) === FALSE) {

                // Add class parent group membership.
                $group
                  ->addMember($user);
              }
            }
          }
        }
      } catch (\Exception $e) {
        \Drupal::logger('opigno_learning_path')
          ->error($e
          ->getMessage());
        \Drupal::messenger()
          ->addMessage($e
          ->getMessage(), 'error');
      }
    }
  }
  if ($entity
    ->bundle() == 'learning_path-group_membership') {

    // Add new membership of group into statistic.
    $membership_id = $entity
      ->get('entity_id')
      ->getValue()[0]['target_id'];
    $group_id = $entity
      ->get('gid')
      ->getValue()[0]['target_id'];
    opigno_learning_path_save_achievements($group_id, $membership_id);
    $entity
      ->enforceIsNew();
    LearningPathAccess::mergeUserStatus($entity);
  }
}