Example #1
0
 /**
  * Duplicate a competency framework by id.
  *
  * Requires moodle/competency:competencymanage capability at the system context.
  *
  * @param int $id The record to duplicate. All competencies associated and related will be duplicated.
  * @return competency_framework the framework duplicated
  */
 public static function duplicate_framework($id)
 {
     global $DB;
     static::require_enabled();
     $framework = new competency_framework($id);
     require_capability('moodle/competency:competencymanage', $framework->get_context());
     // Starting transaction.
     $transaction = $DB->start_delegated_transaction();
     try {
         // Get a uniq idnumber based on the origin framework.
         $idnumber = competency_framework::get_unused_idnumber($framework->get_idnumber());
         $framework->set_idnumber($idnumber);
         // Adding the suffix copy to the shortname.
         $framework->set_shortname(get_string('duplicateditemname', 'core_competency', $framework->get_shortname()));
         $framework->set_id(0);
         $framework = $framework->create();
         // Array that match the old competencies ids with the new one to use when copying related competencies.
         $frameworkcompetency = competency::get_framework_tree($id);
         $matchids = self::duplicate_competency_tree($framework->get_id(), $frameworkcompetency, 0, 0);
         // Copy the related competencies.
         $relcomps = related_competency::get_multiple_relations(array_keys($matchids));
         foreach ($relcomps as $relcomp) {
             $compid = $relcomp->get_competencyid();
             $relcompid = $relcomp->get_relatedcompetencyid();
             if (isset($matchids[$compid]) && isset($matchids[$relcompid])) {
                 $newcompid = $matchids[$compid]->get_id();
                 $newrelcompid = $matchids[$relcompid]->get_id();
                 if ($newcompid < $newrelcompid) {
                     $relcomp->set_competencyid($newcompid);
                     $relcomp->set_relatedcompetencyid($newrelcompid);
                 } else {
                     $relcomp->set_competencyid($newrelcompid);
                     $relcomp->set_relatedcompetencyid($newcompid);
                 }
                 $relcomp->set_id(0);
                 $relcomp->create();
             } else {
                 // Debugging message when there is no match found.
                 debugging('related competency id not found');
             }
         }
         // Setting rules on duplicated competencies.
         self::migrate_competency_tree_rules($frameworkcompetency, $matchids);
         $transaction->allow_commit();
     } catch (\Exception $e) {
         $transaction->rollback($e);
     }
     // Trigger a competency framework created event.
     \core\event\competency_framework_created::create_from_framework($framework)->trigger();
     return $framework;
 }