public function save(\Doctrine_Connection $conn = null, $withparams = true)
 {
     $new = $this->isNew();
     if ($conn == null) {
         $conn = Doctrine_Manager::connection();
     }
     $conn->beginTransaction();
     try {
         if ($new && $withparams) {
             $params = Doctrine_Core::getTable('EiFunctionHasParam')->findByFunctionRefAndFunctionIdAndParamType($this->function_ref, $this->function_id, "IN");
             //pour chaque paramètres associé à la fonction en provenance de script
             $params_collection = new Doctrine_Collection('EiParam');
             foreach ($params as $p => $param) {
                 $eiParam = new EiParam();
                 $eiParam->setEiFonction($this);
                 $eiParam->setParamId($param->getParamId());
                 $eiParam->setValeur($param->getDefaultValue());
                 $eiParam->setName($param->getName());
                 $params_collection->add($eiParam);
             }
             $this->setEiParams($params_collection);
             $params = Doctrine_Core::getTable('EiFunctionHasParam')->findByFunctionRefAndFunctionIdAndParamType($this->function_ref, $this->function_id, "OUT");
             $mappingCollection = new Doctrine_Collection("EiParamBlockFunctionMapping");
             /** @var EiFunctionHasParam $param */
             foreach ($params as $param) {
                 $mapping = new EiParamBlockFunctionMapping();
                 $mapping->setEiParamFunctionId($param->getParamId());
                 $mapping->setEiFunction($this);
                 $mappingCollection->add($mapping);
             }
             $this->setEiFunctionMapping($mappingCollection);
         }
         parent::save($conn);
         if ($new) {
             $this->getEiVersionStructure()->setEiFonctionId($this->getId());
         }
         $conn->commit();
     } catch (Exception $e) {
         //            $conn->rollback();
         throw $e;
     }
     return $this;
 }
 /**
  * @param EiVersion $copie
  * @param Doctrine_Connection $conn
  * @param null $ei_scenario_id
  * @param array $allowedTypes
  * @return EiVersion
  * @throws Exception
  */
 public function createStructureCopy(EiVersion $copie, Doctrine_Connection $conn = null, $ei_scenario_id = null, array $allowedTypes = array())
 {
     /** @var sfLogger $logger */
     $logger = sfContext::getInstance()->getLogger();
     // Déclaration de la table EiVersionStructure.
     /** @var EiVersionStructureTable $tableVersionStr */
     $tableVersionStr = Doctrine_Core::getTable('EiVersionStructure');
     // Tableau des correspondances.
     $correspondances = array();
     $correspondancesF = array();
     $version_id = $this->old_version_id == false ? $this->getId() : $this->old_version_id;
     $allowedTypes = count($allowedTypes) == 0 ? EiVersionStructure::getAllTypes() : $allowedTypes;
     $ignored = 0;
     //*******************************************************//
     //**********          COPIE STRUCTURE          **********//
     //*******************************************************//
     $logger->info("--------------------------------------------");
     $logger->info("----------     COPIE SCENARIO     ----------");
     $logger->info("--------------------------------------------");
     // Création d'une collection de structure de version.
     /** @var Doctrine_Collection $nouvelleStructure */
     $nouvelleStructure = new Doctrine_Collection('EiVersionStructure');
     // Variable temporaire contenant le noeud père.
     /** @var EiVersionStructure $ei_version_str_prec */
     $ei_version_str_prec = null;
     // Variable temporaire contenant le niveau où l'on se situait dans l'arbre à la boucle précédente.
     $level_prec = 0;
     // Variables temporaires.
     /** @var EiVersionStructure $parent */
     $root_id = $parent = null;
     // On récupère la structure complète de la version actuelle.
     $currentVersionTree = $tableVersionStr->getEiVersionTree($version_id, $allowedTypes);
     // On parcourt chaque élément.
     /** @var EiVersionStructure $ei_version_str */
     foreach ($currentVersionTree as $i => $ei_version_str) {
         $logger->info("----------     PARCOURS ELT STRUCTURE N° " . $ei_version_str->getId() . "     ----------");
         if (in_array($ei_version_str->getType(), $allowedTypes)) {
             //*************************************************************//
             //**********          DETERMINATION DU PERE          **********//
             //*************************************************************//
             // Si le niveau précédent est inférieur au niveau parcouru, alors, le parent est la dernière version structure.
             if ($ei_version_str->getLevel() > $level_prec) {
                 $parent = $ei_version_str_prec;
             } elseif ($ei_version_str->getLevel() < $level_prec) {
                 // On réalise la différence entre les deux niveau.
                 $j = $level_prec - $ei_version_str->getLevel();
                 // On remonte d'autant de fois afin de récupérer le père.
                 while ($j > 0) {
                     $parent = $parent->getNode()->getParent();
                     $j--;
                 }
             }
             //*******************************************************************************//
             //**********          ENREGISTREMENT DES INFORMATIONS DE BASE          **********//
             //*******************************************************************************//
             $strElementCopie = new EiVersionStructure();
             $strElementCopie->setRootId($root_id);
             $strElementCopie->setLft($ei_version_str->getLft());
             $strElementCopie->setRgt($ei_version_str->getRgt());
             $strElementCopie->setLevel($ei_version_str->getLevel());
             $strElementCopie->setName($ei_version_str->getName());
             $strElementCopie->setDescription($ei_version_str->getDescription());
             $strElementCopie->setSlug($ei_version_str->getSlug());
             $strElementCopie->setEiVersion($copie);
             $strElementCopie->setType($ei_version_str->getType());
             // Si l'élément possède un père, on le précise.
             if ($parent) {
                 $strElementCopie->setEiVersionStructureParentId($parent->getId());
             }
             // On sauvegarde l'élément.
             $strElementCopie->save($conn);
             // Mise à jour du tableau des correspondances.
             $correspondances[$ei_version_str->getId()] = $strElementCopie->getId();
             //**********************************************************//
             //**********          CREATION FONCTION          ***********//
             //**********************************************************//
             // S'il s'agit d'une fonction, on crée la copie.
             if ($ei_version_str->isEiFonction()) {
                 $logger->info("----------     CREATION FONCTION     ----------");
                 $fct = $ei_version_str->getEiFonction()->createCopie($strElementCopie, $conn);
                 $strElementCopie->setEiFonctionId($fct->getId());
                 $correspondancesF[$ei_version_str->getEiFonctionId()] = $fct->getId();
             } elseif ($ei_version_str->isEiBlock()) {
                 $logger->info("----------     CREATION BLOCK     ----------");
                 $ei_version_str_prec = $strElementCopie;
             }
             $level_prec = $ei_version_str->getLevel();
             if ($i == 0) {
                 $root_id = $strElementCopie->getId();
                 $strElementCopie->setRootId($root_id);
                 $strElementCopie->save($conn);
             }
             $nouvelleStructure->add($strElementCopie);
         }
     }
     foreach ($currentVersionTree as $i => $ei_version_str) {
         //**********************************************************//
         //**********          CAS BLOCK FOREACH           **********//
         //**********************************************************//
         if ($ei_version_str->getType() == EiVersionStructure::$TYPE_FOREACH) {
             $logger->info("----------     CREATION FOREACH     ----------");
             /** @var EiMappingStructureSyncIn $oldMapping */
             $oldMapping = $ei_version_str->getEiVersionStructureDataSetMapping()->getFirst();
             $mapping = new EiMappingStructureSyncIn();
             $mapping->setEiDatasetStructureId($oldMapping->getEiDatasetStructureId());
             $mapping->setEiVersionStructureId($correspondances[$ei_version_str->getId()]);
             $mapping->save($conn);
         } elseif ($ei_version_str->isEiBlockParam()) {
             $logger->info("----------     CREATION BLOCK PARAM     ----------");
             // Copie des mappings IN et OUT.
             /** @var EiBlockDataSetMapping $oldMappingIn */
             $oldMappingIn = $ei_version_str->getMappingDataSet(EiBlockDataSetMapping::$TYPE_IN);
             /** @var EiBlockDataSetMapping $oldMappingOut */
             $oldMappingOut = $ei_version_str->getMappingDataSet(EiBlockDataSetMapping::$TYPE_OUT);
             if ($oldMappingIn != null) {
                 $logger->info("----------     MAPPING IN :  " . $oldMappingIn->getEiDatasetStructureId() . " / " . $correspondances[$ei_version_str->getId()] . "    ----------");
                 $newMappingIn = new EiMappingStructureSyncIn();
                 $newMappingIn->setEiDatasetStructureId($oldMappingIn->getEiDatasetStructureId());
                 $newMappingIn->setEiVersionStructureId($correspondances[$ei_version_str->getId()]);
                 $newMappingIn->save($conn);
             }
             if ($oldMappingOut != null) {
                 $logger->info("----------     MAPPING OUT :  " . $oldMappingOut->getEiDatasetStructureId() . " / " . $correspondances[$ei_version_str->getId()] . "    ----------");
                 $newMappingOut = new EiMappingStructureSyncOut();
                 $newMappingOut->setEiDatasetStructureId($oldMappingOut->getEiDatasetStructureId());
                 $newMappingOut->setEiVersionStructureId($correspondances[$ei_version_str->getId()]);
                 $newMappingOut->save($conn);
             }
         } elseif ($ei_version_str->isEiFonction() && in_array($ei_version_str->getType(), $allowedTypes)) {
             $logger->info("----------     CREATION PARAM FONCTION     ----------");
             // Récupération de l'ensemble des paramètres OUT.
             /** @var EiParamBlockFunctionMapping[] $outParams */
             $outParams = $ei_version_str->getEiFonction()->getEiFunctionMapping();
             $logger->info("----------     " . count($outParams) . " PARAMS.");
             // Copie de chaque paramètre de mapping OUT.
             /** @var EiParamBlockFunctionMapping $oldMapping */
             foreach ($outParams as $oldMapping) {
                 if ($oldMapping->getEiFunctionId() != "" && $oldMapping->getEiParamFunctionId() != "") {
                     /** @var EiParamBlockFunctionMapping $mapping */
                     $mapping = new EiParamBlockFunctionMapping();
                     $mapping->setEiParamBlockId($oldMapping->getEiParamBlockId() == "" ? null : $correspondances[$oldMapping->getEiParamBlockId()]);
                     $mapping->setEiFunctionId($correspondancesF[$oldMapping->getEiFunctionId()]);
                     $mapping->setEiParamFunctionId($oldMapping->getEiParamFunctionId());
                     $mapping->save($conn);
                 }
             }
         } elseif (!in_array($ei_version_str->getType(), $allowedTypes)) {
             $ignored++;
         }
     }
     // On affecte à la copie la structure complète.
     $copie->setEiVersionStructures($nouvelleStructure);
     // Sauvegarde de la copie de version.
     $copie->save($conn);
     //*****************************************************//
     //**********          VERIFICATIONS          **********//
     //*****************************************************//
     // On récupère l'arbre de la structure de la copie.
     $arbreNouvelleVersion = $tableVersionStr->getEiVersionTree($copie->getId());
     // On vérifie que le nombre d'éléments est le même de chaque côté sinon on lève une exception.
     if (count($currentVersionTree) != count($arbreNouvelleVersion) + $ignored) {
         throw new Exception('Version copie failed');
     }
     return $copie;
 }
 public function getFullFonctions($ei_version_structure, $defaultPackage = null)
 {
     /* On s'assure que tout marche bien même si le package par défaut n'est pas renseigné */
     if ($defaultPackage == null) {
         $defPackId = 0;
         $defPackRef = 0;
         $defInterventionId = 0;
     } else {
         $defPackId = $defaultPackage['package_id'];
         $defPackRef = $defaultPackage['package_ref'];
         $defInterventionId = $defaultPackage['subject_id'];
     }
     $query = "\n        SELECT  fct.*, t.name as fctname,\n                ep.param_id as ep_paramid, ep.param_type, ep.name as paramname, ep.default_value as paramdefaultvalue, ep.description as paramdescription,\n                p.valeur, p.id as id_eiparam, p.param_id, p.observation,\n                mapping.id as id_mapping, mapping.ei_param_function_id, mapping.ei_param_block_id as mapping_ei_param_block_id, mapping.expression as mapping_expression,\n                mapping.ei_function_id as mapping_ei_function_id,\n                sf.subject_id as sf_subject_id ,sf.function_id as sf_function_id,sf.function_ref as sf_function_ref,\n                IF(sc.ticket_id IS NOT NULL and sc.ticket_ref IS NOT NULL,1,IF(sf.automate IS NOT NULL,0,NULL)) as  sf_automate,\n                s.id as s_id,s.name as s_name  ,s.package_id as s_package_id   ,s.package_ref as s_package_ref \n        FROM ei_fonction fct\n\n        INNER JOIN ei_version_structure ei_str\n        ON ei_str.ei_fonction_id = fct.id\n\n        LEFT JOIN ei_function_has_param ep\n        ON fct.function_ref = ep.function_ref AND ep.function_id = fct.function_id\n\n        LEFT JOIN ei_param p\n        ON p.param_id = ep.param_id AND p.id_fonction = fct.id\n\n        LEFT JOIN ei_param_block_function_mapping mapping\n        ON mapping.ei_function_id = fct.id AND mapping.ei_param_function_id = ep.param_id\n\n        LEFT JOIN ei_tree t\n        ON fct.function_ref=t.ref_obj  AND fct.function_id=t.obj_id\n        left join ei_script sc on sc.function_id=fct.function_id and sc.function_ref=fct.function_ref and sc.ticket_id=" . $defPackId . " and sc.ticket_ref=" . $defPackRef . " \n        left join ei_subject_functions sf on sf.function_id=fct.function_id and sf.function_ref=fct.function_ref  and sf.subject_id=" . $defInterventionId . " \n        left join ei_subject s on s.id=sf.subject_id and s.id=" . $defInterventionId . " and s.package_id=" . $defPackId . " and s.package_ref=" . $defPackRef . "\n            \n        WHERE ei_str.ei_version_structure_parent_id = " . $ei_version_structure->getId() . "\n        ORDER BY ei_str.lft\n        ";
     $fonctions = Doctrine_Manager::getInstance()->getCurrentConnection()->fetchAll($query);
     $fctArray = array();
     $count = count($fonctions);
     $i = 0;
     $params = new Doctrine_Collection('EiParamBlockFunctionMapping');
     $mappings = new Doctrine_Collection('EiParamBlockFunctionMapping');
     $paramsRegistered = array();
     $mappingsRegistered = array();
     $subjectFonctions = array();
     while ($i < $count) {
         $j = $i;
         $fct = $fonctions[$i];
         while ($j < $count && $fct['id'] == $fonctions[$j]['id']) {
             if ($fonctions[$j]['id_eiparam'] != null && !in_array($fonctions[$j]['id_eiparam'], $paramsRegistered)) {
                 $param = new EiParam();
                 $paramsRegistered[] = $fonctions[$j]["id_eiparam"];
                 $param->setId($fonctions[$j]['id_eiparam']);
                 $param->setIdFonction($fonctions[$j]['id']);
                 $param->setParamId($fonctions[$j]['param_id']);
                 $param->setValeur($fonctions[$j]['valeur']);
                 $param->setObservation($fonctions[$j]['observation']);
                 $param->setName($fonctions[$j]['paramname']);
                 $param->setDescription($fonctions[$j]['paramdescription']);
                 $param->setDefaultValue($fonctions[$j]['paramdefaultvalue']);
                 $params->add($param);
             }
             if ($fonctions[$j]["id_mapping"] != null && !in_array($fonctions[$j]["id_mapping"], $mappingsRegistered)) {
                 $mapping = new EiParamBlockFunctionMapping();
                 $mappingsRegistered[] = $fonctions[$j]["id_mapping"];
                 $mapping->setId($fonctions[$j]["id_mapping"]);
                 $mapping->setEiParamFunctionId($fonctions[$j]["ei_param_function_id"]);
                 $mapping->setEiFunctionId($fonctions[$j]["mapping_ei_function_id"]);
                 $mapping->setExpression($fonctions[$j]["mapping_expression"]);
                 if ($fonctions[$j]["mapping_ei_param_block_id"] != null) {
                     $mapping->setEiParamBlockId($fonctions[$j]["mapping_ei_param_block_id"]);
                 }
                 $mappings->add($mapping);
             }
             if ($fonctions[$j]["sf_automate"] != null && !in_array($defInterventionId, $subjectFonctions)) {
                 $subjectFonctions[] = array('sf_subject_id' => $defInterventionId, 'sf_function_id' => $fonctions[$j]["function_id"], 'sf_function_ref' => $fonctions[$j]["function_ref"], 'sf_automate' => $fonctions[$j]["sf_automate"]);
             }
             $j++;
         }
         $aux = new EiFonction();
         $aux->setId($fct['id']);
         $aux->setSubjectFunctions($subjectFonctions);
         $aux->setFunctionId($fct['function_id']);
         $aux->setFunctionRef($fct['function_ref']);
         $aux->setDescription($fct['description']);
         $aux->setProjectId($fct['project_id']);
         $aux->setProjectRef($fct['project_ref']);
         $aux->setName($fct['fctname']);
         $aux->setEiVersionStructureId($fct["ei_version_structure_id"]);
         $aux->setEiParams($params);
         $aux->setEiFunctionMapping($mappings);
         $params = new Doctrine_Collection('EiParam');
         $mappings = new Doctrine_Collection('EiParamBlockFunctionMapping');
         $paramsRegistered = array();
         $mappingsRegistered = array();
         $fctArray[] = $aux;
         $i = $j;
         $subjectFonctions = array();
     }
     return $fctArray;
 }