You are here

public function OpignoModuleController::activitiesToModule in Opigno module 8

Same name and namespace in other branches
  1. 3.x src/Controller/OpignoModuleController.php \Drupal\opigno_module\Controller\OpignoModuleController::activitiesToModule()

Add activities to existing module.

Parameters

array $activities: Array of activities that will be added.

\Drupal\opigno_module\Entity\OpignoModuleInterface $module: Opigno module entity object.

null|Group $group: Training ID.

null|int $max_score:

Return value

bool Activities to module flag.

Throws

\Exception

File

src/Controller/OpignoModuleController.php, line 88

Class

OpignoModuleController
Class OpignoModuleController.

Namespace

Drupal\opigno_module\Controller

Code

public function activitiesToModule(array $activities, OpignoModuleInterface $module, Group $group = NULL, $max_score = 10) {

  /* @var $connection \Drupal\Core\Database\Connection */
  $connection = \Drupal::service('database');
  $module_activities_fields = [];
  foreach ($activities as $activity) {
    if ($activity instanceof OpignoActivityInterface) {

      /* @todo Use version ID instead of reuse of ID. */
      $module_activity_fields['parent_id'] = $module
        ->id();
      $module_activity_fields['parent_vid'] = $module
        ->getRevisionId();
      $module_activity_fields['child_id'] = $activity
        ->id();
      $module_activity_fields['child_vid'] = $activity
        ->getRevisionId();
      $module_activity_fields['max_score'] = $max_score;
      $module_activity_fields['group_id'] = is_object($group) ? $group
        ->id() : $group;
      $module_activities_fields[] = $module_activity_fields;
    }
  }
  if (!empty($module_activities_fields)) {
    $insert_query = $connection
      ->insert('opigno_module_relationship')
      ->fields([
      'parent_id',
      'parent_vid',
      'child_id',
      'child_vid',
      'max_score',
      'group_id',
    ]);
    foreach ($module_activities_fields as $module_activities_field) {
      $insert_query
        ->values($module_activities_field);
    }
    try {
      $insert_query
        ->execute();
    } catch (\Exception $e) {
      \Drupal::messenger()
        ->addMessage($e
        ->getMessage(), 'error');
      return FALSE;
    }

    // Set activities weight.
    if (empty($e)) {
      $activities = $module
        ->getModuleActivities();
      if ($activities) {
        $weight = -1000;
        foreach ($activities as $activity) {
          if (!empty($activity->omr_id)) {
            $connection
              ->merge('opigno_module_relationship')
              ->keys([
              'omr_id' => $activity->omr_id,
            ])
              ->fields([
              'weight' => $weight,
            ])
              ->execute();
            $weight++;
          }
        }
      }
    }
  }
  return TRUE;
}