Passed
Push — master ( e739b7...1cdc43 )
by Julito
10:11
created

UniqueAnswerNoOption::processAnswersCreation()   D

Complexity

Conditions 11
Paths 388

Size

Total Lines 110
Code Lines 59

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 11
eloc 59
nc 388
nop 2
dl 0
loc 110
rs 4.2012
c 0
b 0
f 0

How to fix   Long Method    Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
/* For licensing terms, see /license.txt */
3
4
use ChamiloSession as Session;
5
6
/**
7
 * Class UniqueAnswerNoOption
8
 * Allows to instantiate an object of type UNIQUE_ANSWER (MULTIPLE CHOICE, UNIQUE ANSWER),
9
 * extending the class question.
10
 *
11
 * @author Eric Marguin
12
 * @author Julio Montoya
13
 *
14
 * @package chamilo.exercise
15
 */
16
class UniqueAnswerNoOption extends Question
17
{
18
    public static $typePicture = 'mcuao.png';
19
    public static $explanationLangVar = 'UniqueAnswerNoOption';
20
21
    /**
22
     * Constructor.
23
     */
24
    public function __construct()
25
    {
26
        parent::__construct();
27
        $this->type = UNIQUE_ANSWER_NO_OPTION;
28
        $this->isContent = $this->getIsContent();
29
    }
30
31
    /**
32
     * {@inheritdoc}
33
     */
34
    public function createAnswersForm($form)
35
    {
36
        // getting the exercise list
37
        $obj_ex = Session::read('objExercise');
38
39
        $editor_config = [
40
            'ToolbarSet' => 'TestProposedAnswer',
41
            'Width' => '100%',
42
            'Height' => '125',
43
        ];
44
        // This line define how many question by default appear when creating a choice question
45
        // The previous default value was 2. See task #1759.
46
        $nb_answers = isset($_POST['nb_answers']) ? (int) $_POST['nb_answers'] : 3;
47
        $nb_answers += (isset($_POST['lessAnswers']) ? -1 : (isset($_POST['moreAnswers']) ? 1 : 0));
48
49
        /*
50
          Types of Feedback
51
          $feedback_option[0]=get_lang('Feedback');
52
          $feedback_option[1]=get_lang('DirectFeedback');
53
          $feedback_option[2]=get_lang('NoFeedback');
54
         */
55
56
        $feedback_title = '';
57
        if ($obj_ex->selectFeedbackType() == 1) {
58
            $editor_config['Width'] = '250';
59
            $editor_config['Height'] = '110';
60
            $comment_title = '<th width="50%" >'.get_lang('Comment').'</th>';
61
            $feedback_title = '<th width="50%" >'.get_lang('Scenario').'</th>';
62
        } else {
63
            $comment_title = '<th width="50%">'.get_lang('Comment').'</th>';
64
        }
65
66
        $html = '<table class="table table-striped table-hover">';
67
        $html .= '<thead>';
68
        $html .= '<tr>';
69
        $html .= '<th>'.get_lang('Number').'</th>';
70
        $html .= '<th>'.get_lang('True').'</th>';
71
        $html .= '<th width="50%">'.get_lang('Answer').'</th>';
72
        $html .= $comment_title.$feedback_title;
73
        $html .= '<th>'.get_lang('Weighting').'</th>';
74
        $html .= '</tr>';
75
        $html .= '</thead>';
76
        $html .= '<tbody>';
77
78
        $form->addHeader(get_lang('Answers'));
79
        $form->addHtml($html);
80
81
        $defaults = [];
82
        $correct = 0;
83
        $answer = false;
84
        if (!empty($this->id)) {
85
            $answer = new Answer($this->id);
86
            $answer->read();
87
            if ($answer->nbrAnswers > 0 && !$form->isSubmitted()) {
88
                $nb_answers = $answer->nbrAnswers;
89
            }
90
        }
91
92
        $temp_scenario = [];
93
        if ($nb_answers < 1) {
94
            $nb_answers = 1;
95
            echo Display::return_message(get_lang('YouHaveToCreateAtLeastOneAnswer'));
96
        }
97
        $editQuestion = isset($_GET['editQuestion']) ? $_GET['editQuestion'] : false;
98
        if ($editQuestion) {
99
            //fixing $nb_answers
100
            $new_list = [];
101
            $count = 1;
102
            if (isset($_POST['lessAnswers'])) {
103
                if (!isset($_SESSION['less_answer'])) {
104
                    $_SESSION['less_answer'] = $this->id;
105
                    $nb_answers--;
106
                }
107
            }
108
            for ($k = 1; $k <= $nb_answers; $k++) {
109
                if ($answer->position[$k] != '666') {
110
                    $new_list[$count] = $count;
111
                    $count++;
112
                }
113
            }
114
        } else {
115
            for ($k = 1; $k <= $nb_answers; $k++) {
116
                $new_list[$k] = $k;
117
            }
118
        }
119
120
        foreach ($new_list as $key) {
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $new_list does not seem to be defined for all execution paths leading up to this point.
Loading history...
121
            $i = $key;
122
            $form->addElement('html', '<tr>');
123
            if (is_object($answer)) {
124
                if ($answer->position[$i] == 666) {
125
                    //we set nothing
126
                } else {
127
                    if ($answer->correct[$i]) {
128
                        $correct = $i;
129
                    }
130
                    $answer_result = $answer->answer[$i];
131
                    $weight_result = float_format($answer->weighting[$i], 1);
132
                    if ($nb_answers == $i) {
133
                        $weight_result = '0';
134
                    }
135
136
                    $defaults['answer['.$i.']'] = $answer_result;
137
                    $defaults['comment['.$i.']'] = $answer->comment[$i];
138
                    $defaults['weighting['.$i.']'] = $weight_result;
139
140
                    $item_list = explode('@@', $answer->destination[$i]);
141
142
                    $try = $item_list[0];
143
                    $lp = $item_list[1];
144
                    $list_dest = $item_list[2];
145
                    $url = $item_list[3];
146
147
                    if ($try == 0) {
148
                        $try_result = 0;
149
                    } else {
150
                        $try_result = 1;
151
                    }
152
153
                    if ($url == 0) {
154
                        $url_result = '';
155
                    } else {
156
                        $url_result = $url;
157
                    }
158
159
                    $temp_scenario['url'.$i] = $url_result;
160
                    $temp_scenario['try'.$i] = $try_result;
161
                    $temp_scenario['lp'.$i] = $lp;
162
                    $temp_scenario['destination'.$i] = $list_dest;
163
                }
164
            }
165
166
            $defaults['scenario'] = $temp_scenario;
167
            $renderer = &$form->defaultRenderer();
168
169
            $renderer->setElementTemplate(
170
                '<td><!-- BEGIN error --><span class="form_error">{error}</span><!-- END error --><br/>{element}</td>',
171
                'correct'
172
            );
173
            $renderer->setElementTemplate(
174
                '<td><!-- BEGIN error --><span class="form_error">{error}</span><!-- END error --><br/>{element}</td>',
175
                'counter['.$i.']'
176
            );
177
            $renderer->setElementTemplate(
178
                '<td><!-- BEGIN error --><span class="form_error">{error}</span><!-- END error --><br/>{element}</td>',
179
                'answer['.$i.']'
180
            );
181
            $renderer->setElementTemplate(
182
                '<td><!-- BEGIN error --><span class="form_error">{error}</span><!-- END error --><br/>{element}</td>',
183
                'comment['.$i.']'
184
            );
185
            $renderer->setElementTemplate(
186
                '<td><!-- BEGIN error --><span class="form_error">{error}</span><!-- END error --><br/>{element}</td>',
187
                'weighting['.$i.']'
188
            );
189
190
            $answer_number = $form->addElement('text', 'counter['.$i.']', null, 'value="'.$i.'"');
191
            $answer_number->freeze();
192
193
            $form->addElement('radio', 'correct', null, null, $i, 'class="checkbox" style="margin-left: 0em;"');
194
            $form->addElement('html_editor', 'answer['.$i.']', null, [], $editor_config);
195
196
            $form->addElement('html_editor', 'comment['.$i.']', null, [], $editor_config);
197
            $form->addElement('text', 'weighting['.$i.']', null, ['style' => 'width: 60px;', 'value' => '0']);
198
            $form->addElement('html', '</tr>');
199
            $i++;
200
        }
201
202
        if (empty($this->id)) {
203
            $form->addElement('hidden', 'new_question', 1);
204
        }
205
206
        //Adding the "I don't know" question answer
207
        //if (empty($this -> id)) {
208
        $i = 666;
209
        $form->addHtml('<tr>');
210
211
        $defaults["counter[$i]"] = '-';
212
        $defaults['answer['.$i.']'] = get_lang('DontKnow');
213
        $defaults['weighting['.$i.']'] = '0';
214
        $defaults['scenario'] = $temp_scenario;
215
        $renderer = &$form->defaultRenderer();
216
217
        $renderer->setElementTemplate(
218
            '<td><!-- BEGIN error --><span class="form_error">{error}</span><!-- END error --><br/>{element}</td>',
219
            'correct'
220
        );
221
        $renderer->setElementTemplate(
222
            '<td><!-- BEGIN error --><span class="form_error">{error}</span><!-- END error --><br/>{element}</td>',
223
            'counter['.$i.']'
224
        );
225
        $renderer->setElementTemplate(
226
            '<td><!-- BEGIN error --><span class="form_error">{error}</span><!-- END error --><br/>{element}</td>',
227
            'answer['.$i.']'
228
        );
229
        $renderer->setElementTemplate(
230
            '<td><!-- BEGIN error --><span class="form_error">{error}</span><!-- END error --><br/>{element}</td>',
231
            'comment['.$i.']'
232
        );
233
        $renderer->setElementTemplate(
234
            '<td><!-- BEGIN error --><span class="form_error">{error}</span><!-- END error --><br/>{element}</td>',
235
            'weighting['.$i.']'
236
        );
237
238
        $form
239
            ->addElement('text', 'counter['.$i.']', null)
240
            ->freeze();
241
242
        $form->addElement('hidden', 'position['.$i.']', '666');
243
        $form->addElement('radio', 'correct', null, null, $i, ['class' => 'checkbox', 'disabled' => true]);
244
        $form->addElement('html_editor', 'answer['.$i.']', null, [], $editor_config);
245
246
        $form->addRule('answer['.$i.']', get_lang('ThisFieldIsRequired'), 'required');
247
        $form->addElement('html_editor', 'comment['.$i.']', null, [], $editor_config);
248
        $form->addElement('text', "weighting[$i]", null)->freeze();
249
250
        $form->addHTml('</tr>');
251
        $form->addHtml('</tbody></table>');
252
253
        $buttonGroup = [];
254
255
        global $text;
256
        //ie6 fix
257
        if ($obj_ex->edit_exercise_in_lp == true ||
258
            (empty($this->exerciseList) && empty($obj_ex->id))
259
        ) {
260
            //setting the save button here and not in the question class.php
261
            $buttonGroup[] = $form->addButtonDelete(get_lang('LessAnswer'), 'lessAnswers', true);
262
            $buttonGroup[] = $form->addButtonCreate(get_lang('PlusAnswer'), 'moreAnswers', true);
263
            $buttonGroup[] = $form->addButtonSave($text, 'submitQuestion', true);
264
265
            $form->addGroup($buttonGroup);
266
        }
267
268
        //We check the first radio button to be sure a radio button will be check
269
        if ($correct == 0) {
270
            $correct = 1;
271
        }
272
        $defaults['correct'] = $correct;
273
274
        if (!empty($this->id)) {
275
            $form->setDefaults($defaults);
276
        } else {
277
            $form->setDefaults($defaults);
278
        }
279
280
        $form->addElement('hidden', 'nb_answers');
281
        $form->setConstants(['nb_answers' => $nb_answers]);
282
    }
283
284
    /**
285
     * {@inheritdoc}
286
     */
287
    public function processAnswersCreation($form, $exercise)
288
    {
289
        $questionWeighting = $nbrGoodAnswers = 0;
290
        $correct = $form->getSubmitValue('correct');
291
        $objAnswer = new Answer($this->id);
292
        $nb_answers = $form->getSubmitValue('nb_answers');
293
        $minus = 1;
294
        if ($form->getSubmitValue('new_question')) {
295
            $minus = 0;
296
        }
297
298
        for ($i = 1; $i <= $nb_answers - $minus; $i++) {
299
            $position = trim($form->getSubmitValue('position['.$i.']'));
300
            $answer = trim($form->getSubmitValue('answer['.$i.']'));
301
            $comment = trim($form->getSubmitValue('comment['.$i.']'));
302
            $weighting = trim($form->getSubmitValue('weighting['.$i.']'));
303
            $scenario = $form->getSubmitValue('scenario');
304
305
            //$list_destination = $form -> getSubmitValue('destination'.$i);
306
            //$destination_str = $form -> getSubmitValue('destination'.$i);
307
308
            $try = $scenario['try'.$i];
309
            $lp = $scenario['lp'.$i];
310
            $destination = $scenario['destination'.$i];
311
            $url = trim($scenario['url'.$i]);
312
313
            /*
314
            How we are going to parse the destination value
315
316
            here we parse the destination value which is a string
317
            1@@3@@2;4;4;@@http://www.chamilo.org
318
319
            where: try_again@@lp_id@@selected_questions@@url
320
321
            try_again = is 1 || 0
322
            lp_id = id of a learning path (0 if dont select)
323
            selected_questions= ids of questions
324
            url= an url
325
            */
326
            /*
327
            $destination_str='';
328
            foreach ($list_destination as $destination_id)
329
            {
330
                $destination_str.=$destination_id.';';
331
            }*/
332
            $goodAnswer = ($correct == $i) ? true : false;
333
334
            if ($goodAnswer) {
335
                $nbrGoodAnswers++;
336
                $weighting = abs($weighting);
337
                if ($weighting > 0) {
338
                    $questionWeighting += $weighting;
339
                }
340
            }
341
342
            if (empty($try)) {
343
                $try = 0;
344
            }
345
346
            if (empty($lp)) {
347
                $lp = 0;
348
            }
349
350
            if (empty($destination)) {
351
                $destination = 0;
352
            }
353
354
            if ($url == '') {
355
                $url = 0;
356
            }
357
358
            //1@@1;2;@@2;4;4;@@http://www.chamilo.org
359
            $dest = $try.'@@'.$lp.'@@'.$destination.'@@'.$url;
360
            $objAnswer->createAnswer(
361
                $answer,
362
                $goodAnswer,
363
                $comment,
364
                $weighting,
0 ignored issues
show
Bug introduced by
It seems like $weighting can also be of type double and string; however, parameter $weighting of Answer::createAnswer() does only seem to accept integer, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

364
                /** @scrutinizer ignore-type */ $weighting,
Loading history...
365
                $i,
366
                null,
367
                null,
368
                $dest
369
            );
370
        }
371
372
        //Create 666 answer
373
        $i = 666;
374
        $answer = trim($form->getSubmitValue('answer['.$i.']'));
375
        $comment = trim($form->getSubmitValue('comment['.$i.']'));
376
        $weighting = trim($form->getSubmitValue('weighting['.$i.']'));
377
        $goodAnswer = $correct == $i ? true : false;
378
        $dest = '';
379
380
        $objAnswer->createAnswer(
381
            $answer,
382
            $goodAnswer,
383
            $comment,
384
            $weighting,
385
            $i,
386
            null,
387
            null,
388
            $dest
389
        );
390
391
        // saves the answers into the data base
392
        $objAnswer->save();
393
394
        // sets the total weighting of the question
395
        $this->updateWeighting($questionWeighting);
0 ignored issues
show
Bug introduced by
It seems like $questionWeighting can also be of type double; however, parameter $weighting of Question::updateWeighting() does only seem to accept integer, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

395
        $this->updateWeighting(/** @scrutinizer ignore-type */ $questionWeighting);
Loading history...
396
        $this->save($exercise);
397
    }
398
399
    /**
400
     * {@inheritdoc}
401
     */
402
    public function return_header($exercise, $counter = null, $score = null)
403
    {
404
        $header = parent::return_header($exercise, $counter, $score);
405
        $header .= '<table class="'.$this->question_table_class.'"><tr>';
406
407
        if ($exercise->results_disabled != RESULT_DISABLE_SHOW_ONLY_IN_CORRECT_ANSWER) {
408
            $header .= '<th>'.get_lang('Choice').'</th>';
409
            $header .= '<th>'.get_lang('ExpectedChoice').'</th>';
410
        }
411
        $header .= '<th>'.get_lang('Answer').'</th>';
412
        if ($exercise->showExpectedChoice()) {
413
            $header .= '<th>'.get_lang('Status').'</th>';
414
        }
415
        $header .= '<th>'.get_lang('Comment').'</th>';
416
        $header .= '</tr>';
417
418
        return $header;
419
    }
420
}
421