Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.
Common duplication problems, and corresponding solutions are:
Complex classes like MoodleImport often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes. You can also have a look at the cohesion graph to spot any un-connected, or weakly-connected components.
Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.
While breaking up the class, it is a good idea to analyze how other classes use MoodleImport, and based on these observations, apply Extract Interface, too.
1 | <?php |
||
11 | class MoodleImport |
||
12 | { |
||
13 | /** |
||
14 | * Read and validate the moodleFile |
||
15 | * |
||
16 | * @param resource $uploadedFile *.* mbz file moodle course backup |
||
17 | * @return bool |
||
18 | */ |
||
19 | public function readMoodleFile($uploadedFile) |
||
20 | { |
||
21 | $file = $uploadedFile['tmp_name']; |
||
22 | |||
23 | if (is_file($file) && is_readable($file)) { |
||
24 | $package = new PclZip($file); |
||
25 | $packageContent = $package->listContent(); |
||
26 | $mainFileKey = 0; |
||
27 | foreach ($packageContent as $index => $value) { |
||
28 | if ($value['filename'] == 'moodle_backup.xml') { |
||
29 | $mainFileKey = $index; |
||
30 | break; |
||
31 | } |
||
32 | } |
||
33 | |||
34 | if (!$mainFileKey) { |
||
35 | Display::addFlash(Display::return_message(get_lang('FailedToImportThisIsNotAMoodleFile'), 'error')); |
||
36 | } |
||
37 | |||
38 | $folder = api_get_unique_id(); |
||
39 | $destinationDir = api_get_path(SYS_ARCHIVE_PATH).$folder; |
||
40 | $coursePath = api_get_path(SYS_COURSE_PATH).api_get_course_path().'/'; |
||
41 | $courseInfo = api_get_course_info(); |
||
42 | |||
43 | mkdir($destinationDir, api_get_permissions_for_new_directories(), true); |
||
44 | |||
45 | $package->extract( |
||
46 | PCLZIP_OPT_PATH, |
||
47 | $destinationDir |
||
48 | ); |
||
49 | |||
50 | $xml = @file_get_contents($destinationDir.'/moodle_backup.xml'); |
||
51 | |||
52 | $doc = new DOMDocument(); |
||
53 | $res = @$doc->loadXML($xml); |
||
54 | if ($res) { |
||
55 | $activities = $doc->getElementsByTagName('activity'); |
||
56 | foreach ($activities as $activity) { |
||
57 | if ($activity->childNodes->length) { |
||
58 | $currentItem = []; |
||
59 | |||
60 | foreach ($activity->childNodes as $item) { |
||
61 | $currentItem[$item->nodeName] = $item->nodeValue; |
||
62 | } |
||
63 | |||
64 | $moduleName = isset($currentItem['modulename']) ? $currentItem['modulename'] : false; |
||
65 | switch ($moduleName) { |
||
66 | case 'forum': |
||
67 | require_once '../forum/forumfunction.inc.php'; |
||
68 | $catForumValues = []; |
||
69 | |||
70 | // Read the current forum module xml. |
||
71 | $moduleDir = $currentItem['directory']; |
||
72 | $moduleXml = @file_get_contents($destinationDir.'/'.$moduleDir.'/'.$moduleName.'.xml'); |
||
73 | $moduleValues = $this->readForumModule($moduleXml); |
||
74 | |||
75 | // Create a Forum category based on Moodle forum type. |
||
76 | $catForumValues['forum_category_title'] = $moduleValues['type']; |
||
77 | $catForumValues['forum_category_comment'] = ''; |
||
78 | $catId = store_forumcategory($catForumValues); |
||
79 | $forumValues = []; |
||
80 | $forumValues['forum_title'] = $moduleValues['name']; |
||
81 | $forumValues['forum_image'] = ''; |
||
82 | $forumValues['forum_comment'] = $moduleValues['intro']; |
||
83 | $forumValues['forum_category'] = $catId; |
||
84 | |||
85 | store_forum($forumValues); |
||
86 | break; |
||
87 | case 'quiz': |
||
|
|||
88 | |||
89 | // Read the current quiz module xml. |
||
90 | // The quiz case is the very complicate process of all the import. |
||
91 | // Please if you want to review the script, try to see the readingXML functions. |
||
92 | // The readingXML functions in this clases do all the mayor work here. |
||
93 | |||
94 | $moduleDir = $currentItem['directory']; |
||
95 | $moduleXml = @file_get_contents($destinationDir.'/'.$moduleDir.'/'.$moduleName.'.xml'); |
||
96 | $questionsXml = @file_get_contents($destinationDir.'/questions.xml'); |
||
97 | $moduleValues = $this->readQuizModule($moduleXml); |
||
98 | |||
99 | // At this point we got all the prepared resources from Moodle file |
||
100 | // $moduleValues variable contains all the necesary info to the quiz import |
||
101 | // var_dump($moduleValues); // <-- uncomment this to see the final array |
||
102 | |||
103 | // Lets do this ... |
||
104 | $exercise = new Exercise(); |
||
105 | $exercise->updateTitle(Exercise::format_title_variable($moduleValues['name'])); |
||
106 | $exercise->updateDescription($moduleValues['intro']); |
||
107 | $exercise->updateAttempts($moduleValues['attempts_number']); |
||
108 | $exercise->updateFeedbackType(0); |
||
109 | |||
110 | // Match shuffle question with chamilo |
||
111 | switch ($moduleValues['shufflequestions']) { |
||
112 | case '0': |
||
113 | $exercise->setRandom(0); |
||
114 | break; |
||
115 | case '1': |
||
116 | $exercise->setRandom(-1); |
||
117 | break; |
||
118 | default: |
||
119 | $exercise->setRandom(0); |
||
120 | } |
||
121 | $exercise->updateRandomAnswers($moduleValues['shuffleanswers']); |
||
122 | // @todo divide to minutes |
||
123 | $exercise->updateExpiredTime($moduleValues['timelimit']); |
||
124 | |||
125 | if ($moduleValues['questionsperpage'] == 1) { |
||
126 | $exercise->updateType(2); |
||
127 | } else { |
||
128 | $exercise->updateType(1); |
||
129 | } |
||
130 | |||
131 | // Create the new Quiz |
||
132 | $exercise->save(); |
||
133 | |||
134 | // Ok, we got the Quiz and create it, now its time to add the Questions |
||
135 | foreach ($moduleValues['question_instances'] as $index => $question) { |
||
136 | $questionsValues = $this->readMainQuestionsXml($questionsXml, $question['questionid']); |
||
137 | $moduleValues['question_instances'][$index] = $questionsValues; |
||
138 | // Set Question Type from Moodle XML element <qtype> |
||
139 | $qType = $moduleValues['question_instances'][$index]['qtype']; |
||
140 | // Add the matched chamilo question type to the array |
||
141 | $moduleValues['question_instances'][$index]['chamilo_qtype'] = $this->matchMoodleChamiloQuestionTypes($qType); |
||
142 | $questionInstance = Question::getInstance($moduleValues['question_instances'][$index]['chamilo_qtype']); |
||
143 | if ($questionInstance) { |
||
144 | $questionInstance->updateTitle($moduleValues['question_instances'][$index]['name']); |
||
145 | $questionInstance->updateDescription($moduleValues['question_instances'][$index]['questiontext']); |
||
146 | $questionInstance->updateLevel(1); |
||
147 | $questionInstance->updateCategory(0); |
||
148 | |||
149 | //Save normal question if NOT media |
||
150 | if ($questionInstance->type != MEDIA_QUESTION) { |
||
151 | $questionInstance->save($exercise->id); |
||
152 | |||
153 | // modify the exercise |
||
154 | $exercise->addToList($questionInstance->id); |
||
155 | $exercise->update_question_positions(); |
||
156 | } |
||
157 | |||
158 | $questionList = $moduleValues['question_instances'][$index]['plugin_qtype_'.$qType.'_question']; |
||
159 | $currentQuestion = $moduleValues['question_instances'][$index]; |
||
160 | |||
161 | $result = $this->processAnswers($questionList, $qType, $questionInstance, $currentQuestion); |
||
162 | } |
||
163 | } |
||
164 | |||
165 | break; |
||
166 | case 'resource': |
||
167 | // Read the current resource module xml. |
||
168 | $moduleDir = $currentItem['directory']; |
||
169 | $moduleXml = @file_get_contents($destinationDir.'/'.$moduleDir.'/'.$moduleName.'.xml'); |
||
170 | $filesXml = @file_get_contents($destinationDir.'/files.xml'); |
||
171 | $moduleValues = $this->readResourceModule($moduleXml); |
||
172 | $mainFileModuleValues = $this->readMainFilesXml($filesXml, $moduleValues['contextid']); |
||
173 | $fileInfo = array_merge($moduleValues, $mainFileModuleValues, $currentItem); |
||
174 | $documentPath = $coursePath.'document/'; |
||
175 | $currentResourceFilePath = $destinationDir.'/files/'; |
||
176 | $dirs = new RecursiveDirectoryIterator($currentResourceFilePath); |
||
177 | foreach (new RecursiveIteratorIterator($dirs) as $file) { |
||
178 | if (is_file($file) && strpos($file, $fileInfo['contenthash']) !== false) { |
||
179 | $files = []; |
||
180 | $files['file']['name'] = $fileInfo['filename']; |
||
181 | $files['file']['tmp_name'] = $file->getPathname(); |
||
182 | $files['file']['type'] = $fileInfo['mimetype']; |
||
183 | $files['file']['error'] = 0; |
||
184 | $files['file']['size'] = $fileInfo['filesize']; |
||
185 | $files['file']['from_file'] = true; |
||
186 | $files['file']['move_file'] = true; |
||
187 | $_POST['language'] = $courseInfo['language']; |
||
188 | $_POST['moodle_import'] = true; |
||
189 | |||
190 | DocumentManager::upload_document( |
||
191 | $files, |
||
192 | '/', |
||
193 | $fileInfo['title'], |
||
194 | '', |
||
195 | null, |
||
196 | null, |
||
197 | true, |
||
198 | true |
||
199 | ); |
||
200 | } |
||
201 | } |
||
202 | |||
203 | break; |
||
204 | case 'url': |
||
205 | // Read the current url module xml. |
||
206 | $moduleDir = $currentItem['directory']; |
||
207 | $moduleXml = @file_get_contents($destinationDir.'/'.$moduleDir.'/'.$moduleName.'.xml'); |
||
208 | $moduleValues = $this->readUrlModule($moduleXml); |
||
209 | $_POST['title'] = $moduleValues['name']; |
||
210 | $_POST['url'] = $moduleValues['externalurl']; |
||
211 | $_POST['description'] = $moduleValues['intro']; |
||
212 | $_POST['category_id'] = 0; |
||
213 | $_POST['target'] = '_blank'; |
||
214 | |||
215 | Link::addlinkcategory("link"); |
||
216 | break; |
||
217 | } |
||
218 | } |
||
219 | } |
||
220 | } else { |
||
221 | return false; |
||
222 | } |
||
223 | } else { |
||
224 | return false; |
||
225 | } |
||
226 | |||
227 | removeDir($destinationDir); |
||
228 | return $packageContent[$mainFileKey]; |
||
229 | } |
||
230 | |||
231 | /** |
||
232 | * Read and validate the forum module XML |
||
233 | * |
||
234 | * @param resource $moduleXml XML file |
||
235 | * @return mixed | array if is a valid xml file, false otherwise |
||
236 | */ |
||
237 | View Code Duplication | public function readForumModule($moduleXml) |
|
257 | |||
258 | /** |
||
259 | * Read and validate the resource module XML |
||
260 | * |
||
261 | * @param resource $moduleXml XML file |
||
262 | * @return mixed | array if is a valid xml file, false otherwise |
||
263 | */ |
||
264 | public function readResourceModule($moduleXml) |
||
287 | |||
288 | /** |
||
289 | * Read and validate the url module XML |
||
290 | * |
||
291 | * @param resource $moduleXml XML file |
||
292 | * @return mixed | array if is a valid xml file, false otherwise |
||
293 | */ |
||
294 | View Code Duplication | public function readUrlModule($moduleXml) |
|
314 | |||
315 | /** |
||
316 | * Read and validate the quiz module XML |
||
317 | * |
||
318 | * @param resource $moduleXml XML file |
||
319 | * @return mixed | array if is a valid xml file, false otherwise |
||
320 | */ |
||
321 | public function readQuizModule($moduleXml) |
||
355 | |||
356 | /** |
||
357 | * Search the current file resource in main Files XML |
||
358 | * |
||
359 | * @param resource $filesXml XML file |
||
360 | * @param int $contextId |
||
361 | * @return mixed | array if is a valid xml file, false otherwise |
||
362 | */ |
||
363 | public function readMainFilesXml($filesXml, $contextId) |
||
407 | |||
408 | /** |
||
409 | * Search the current quiestion resource in main Questions XML |
||
410 | * |
||
411 | * @param resource $questionsXml XML file |
||
412 | * @param int $questionId |
||
413 | * @return mixed | array if is a valid xml file, false otherwise |
||
414 | */ |
||
415 | public function readMainQuestionsXml($questionsXml, $questionId) |
||
469 | |||
470 | /** |
||
471 | * return the correct question type options tag |
||
472 | * |
||
473 | * @param string $questionType name |
||
474 | * @return string question type tag |
||
475 | */ |
||
476 | public function getQuestionTypeOptionsTag($questionType) |
||
488 | |||
489 | /** |
||
490 | * return the correct question type answers tag |
||
491 | * |
||
492 | * @param string $questionType name |
||
493 | * @return string question type tag |
||
494 | */ |
||
495 | public function getQuestionTypeAnswersTag($questionType) |
||
507 | |||
508 | /** |
||
509 | * |
||
510 | * @param string $moodleQuestionType |
||
511 | * @return integer Chamilo question type |
||
512 | */ |
||
513 | public function matchMoodleChamiloQuestionTypes($moodleQuestionType) |
||
532 | |||
533 | /** |
||
534 | * Process Moodle Answers to Chamilo |
||
535 | * |
||
536 | * @param array $questionList |
||
537 | * @param string $questionType |
||
538 | * @param object $questionInstance Question/Answer instance |
||
539 | * @param array $currentQuestion |
||
540 | * @return integer db response |
||
541 | */ |
||
542 | public function processAnswers($questionList, $questionType, $questionInstance, $currentQuestion) |
||
619 | |||
620 | /** |
||
621 | * Process Chamilo Unique Answer |
||
622 | * |
||
623 | * @param object $objAnswer |
||
624 | * @param array $answerValues |
||
625 | * @param integer $position |
||
626 | * @param integer $questionWeighting |
||
627 | * @return integer db response |
||
628 | */ |
||
629 | public function processUniqueAnswer($objAnswer, $answerValues, $position, &$questionWeighting) |
||
652 | |||
653 | /** |
||
654 | * Process Chamilo FillBlanks |
||
655 | * |
||
656 | * @param object $objAnswer |
||
657 | * @param array $question |
||
658 | * @param array $answerValues |
||
659 | * @param string $placeholder |
||
660 | * @param integer $position |
||
661 | * @return integer db response |
||
662 | */ |
||
663 | public function processFillBlanks($objAnswer, $question, $answerValues, &$placeholder, $position) |
||
713 | |||
714 | |||
715 | /** |
||
716 | * Litle utility to delete the unuseful tags |
||
717 | * |
||
718 | * @param $array |
||
719 | * @param $keys |
||
720 | */ |
||
721 | public function traverseArray(&$array, $keys) { |
||
732 | |||
733 | } |
According to the PSR-2, the body of a case statement must start on the line immediately following the case statement.
}
To learn more about the PSR-2 coding standard, please refer to the PHP-Fig.