Completed
Push — master ( 9b8b24...6e1754 )
by Julito
58:58
created

survey_question::preSave()   F

Complexity

Conditions 28
Paths 2304

Size

Total Lines 99
Code Lines 56

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 28
eloc 56
nc 2304
nop 1
dl 0
loc 99
rs 2
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 survey_question
8
 */
9
class survey_question
10
{
11
    /** @var FormValidator */
12
    private $form;
13
    public $buttonList = array();
14
15
    /**
16
     * Generic part of any survey question: the question field
17
     * @param array $surveyData
18
     * @param array $formData
19
     *
20
     * @return FormValidator
21
     */
22
    public function createForm($surveyData, $formData)
23
    {
24
        $action = isset($_GET['action']) ? Security::remove_XSS($_GET['action']) : null;
25
        $questionId = isset($_GET['question_id']) ? intval($_GET['question_id']) : null;
26
        $surveyId = isset($_GET['survey_id']) ? intval($_GET['survey_id']) : null;
27
28
        $toolName = Display::return_icon(
29
            SurveyManager::icon_question(Security::remove_XSS($_GET['type'])),
30
            get_lang(ucfirst(Security::remove_XSS($_GET['type']))),
31
            array('align' => 'middle', 'height' => '22px')
32
        ).' ';
33
34
        if ($action == 'add') {
35
            $toolName .= get_lang('AddQuestion').': ';
36
        } elseif ($action == 'edit') {
37
            $toolName .= get_lang('EditQuestion').': ';
38
        }
39
40
        switch ($_GET['type']) {
41
            case 'yesno':
42
                $toolName .= get_lang('YesNo');
43
                break;
44
            case 'multiplechoice':
45
                $toolName .= get_lang('UniqueSelect');
46
                break;
47
            case 'multipleresponse':
48
                $toolName .= get_lang('MultipleResponse');
49
                break;
50
            default:
51
                $toolName .= get_lang(api_ucfirst(Security::remove_XSS($_GET['type'])));
52
        }
53
54
        $sharedQuestionId = isset($formData['shared_question_id']) ? $formData['shared_question_id'] : null;
55
56
        $url = api_get_self().'?action='.$action.'&type='.Security::remove_XSS($_GET['type']).'&survey_id='.$surveyId.'&question_id='.$questionId.'&'.api_get_cidreq();
57
58
        $form = new FormValidator('question_form', 'post', $url);
59
        $form->addHeader($toolName);
60
        $form->addHidden('survey_id', $surveyId);
61
        $form->addHidden('question_id', $questionId);
62
        $form->addHidden('shared_question_id', Security::remove_XSS($sharedQuestionId));
63
        $form->addHidden('type', Security::remove_XSS($_GET['type']));
64
65
        $config = array(
66
            'ToolbarSet' => 'SurveyQuestion',
67
            'Width' => '100%',
68
            'Height' => '120'
69
        );
70
        $form->addHtmlEditor(
71
            'question',
72
            get_lang('Question'),
73
            true,
74
            false,
75
            $config
76
        );
77
78
        if (api_get_configuration_value('allow_required_survey_questions') &&
79
            in_array($_GET['type'], ['yesno', 'multiplechoice'])) {
80
            $form->addCheckBox('is_required', get_lang('IsMandatory'), get_lang('Yes'));
81
        }
82
83
        // When survey type = 1??
84
        if ($surveyData['survey_type'] == 1) {
85
            $table_survey_question_group = Database::get_course_table(TABLE_SURVEY_QUESTION_GROUP);
86
            $sql = 'SELECT id,name FROM '.$table_survey_question_group.'
87
                    WHERE survey_id = '.(int) $_GET['survey_id'].'
88
                    ORDER BY name';
89
            $rs = Database::query($sql);
90
            $glist = null;
91
            while ($row = Database::fetch_array($rs, 'NUM')) {
92
                $glist .= '<option value="'.$row[0].'" >'.$row[1].'</option>';
93
            }
94
95
            $grouplist = $grouplist1 = $grouplist2 = $glist;
96
            if (!empty($formData['assigned'])) {
97
                $grouplist = str_replace('<option value="'.$formData['assigned'].'"', '<option value="'.$formData['assigned'].'" selected', $glist);
98
            }
99
100
            if (!empty($formData['assigned1'])) {
101
                $grouplist1 = str_replace('<option value="'.$formData['assigned1'].'"', '<option value="'.$formData['assigned1'].'" selected', $glist);
102
            }
103
104
            if (!empty($formData['assigned2'])) {
105
                $grouplist2 = str_replace('<option value="'.$formData['assigned2'].'"', '<option value="'.$formData['assigned2'].'" selected', $glist);
106
            }
107
108
            $this->html .= '	<tr><td colspan="">
0 ignored issues
show
Bug Best Practice introduced by
The property html does not exist on survey_question. Did you maybe forget to declare it?
Loading history...
109
			<fieldset style="border:1px solid black"><legend>'.get_lang('Condition').'</legend>
110
111
			<b>'.get_lang('Primary').'</b><br />
112
			'.'<input type="radio" name="choose" value="1" '.(($formData['choose'] == 1) ? 'checked' : '').
113
                '><select name="assigned">'.$grouplist.'</select><br />';
114
115
            $this->html .= '
116
			<b>'.get_lang('Secondary').'</b><br />
117
			'.'<input type="radio" name="choose" value="2" '.(($formData['choose'] == 2) ? 'checked' : '').
118
                '><select name="assigned1">'.$grouplist1.'</select> '.
119
                '<select name="assigned2">'.$grouplist2.'</select>'
120
                .'</fieldset><br />';
121
        }
122
123
        $this->setForm($form);
124
125
        return $form;
126
    }
127
128
    /**
129
     * Adds submit button
130
     *
131
     */
132
    public function renderForm()
133
    {
134
        if (isset($_GET['question_id']) and !empty($_GET['question_id'])) {
135
136
            /**
137
             * Check if survey has answers first before update it, this is because if you update it, the question
138
             * options will delete and re-insert in database loosing the iid and question_id to verify the correct answers
139
             */
140
            $surveyId = isset($_GET['survey_id']) ? intval($_GET['survey_id']) : 0;
141
            $answersChecker = SurveyUtil::checkIfSurveyHasAnswers($surveyId);
142
143
            if (!$answersChecker) {
144
                $this->buttonList[] = $this->getForm()->addButtonUpdate(get_lang('ModifyQuestionSurvey'), 'save', true);
145
            } else {
146
                $this->getForm()->addHtml('
147
                    <div class="form-group">
148
                        <label class="col-sm-2 control-label"></label>
149
                        <div class="col-sm-8">
150
                            <div class="alert alert-info">' . get_lang('YouCantNotEditThisQuestionBecauseAlreadyExistAnswers').'</div>
151
                        </div>
152
                        <div class="col-sm-2"></div>
153
                    </div>
154
                ');
155
            }
156
        } else {
157
            $this->buttonList[] = $this->getForm()->addButtonSave(get_lang('CreateQuestionSurvey'), 'save', true);
158
        }
159
160
        $this->getForm()->addGroup($this->buttonList, 'buttons');
161
    }
162
163
    /**
164
     * @return FormValidator
165
     */
166
    public function getForm()
167
    {
168
        return $this->form;
169
    }
170
171
    /**
172
     * @param FormValidator $form
173
     */
174
    public function setForm($form)
175
    {
176
        $this->form = $form;
177
    }
178
179
    /**
180
     * @param array $formData
181
     *
182
     * @return mixed
183
     */
184
    public function preSave($formData)
185
    {
186
        $counter = Session::read('answer_count');
187
        $answerList = Session::read('answer_list');
188
189
        if (empty($answerList)) {
190
            $answerList = isset($formData['answers']) ? $formData['answers'] : array();
191
            Session::write('answer_list', $answerList);
0 ignored issues
show
Bug introduced by
It seems like $answerList can also be of type array; however, parameter $value of System\Session::write() does only seem to accept string, 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

191
            Session::write('answer_list', /** @scrutinizer ignore-type */ $answerList);
Loading history...
192
        }
193
194
        if (isset($_POST['answers'])) {
195
            $formData['answers'] = $_POST['answers'];
196
        }
197
198
        if (empty($counter)) {
199
            $counter = count($answerList) - 1;
200
            Session::write('answer_count', $counter);
201
        }
202
203
        // Moving an answer up
204
        if (isset($_POST['move_up']) && $_POST['move_up']) {
205
            foreach ($_POST['move_up'] as $key => & $value) {
206
                $id1 = $key;
207
                $content1 = $formData['answers'][$id1];
208
                $id2 = $key - 1;
209
                $content2 = $formData['answers'][$id2];
210
                $formData['answers'][$id1] = $content2;
211
                $formData['answers'][$id2] = $content1;
212
            }
213
        }
214
215
        // Moving an answer down
216
        if (isset($_POST['move_down']) && $_POST['move_down']) {
217
            foreach ($_POST['move_down'] as $key => & $value) {
218
                $id1 = $key;
219
                $content1 = $formData['answers'][$id1];
220
                $id2 = $key + 1;
221
                $content2 = $formData['answers'][$id2];
222
                $formData['answers'][$id1] = $content2;
223
                $formData['answers'][$id2] = $content1;
224
            }
225
        }
226
227
        /**
228
         * This solution is a little bit strange but I could not find a different solution.
229
         */
230
        if (isset($_POST['delete_answer'])) {
231
            $deleted = false;
232
            foreach ($_POST['delete_answer'] as $key => & $value) {
233
                $deleted = $key;
234
                $counter--;
235
                Session::write('answer_count', $counter);
236
            }
237
238
            foreach ($formData['answers'] as $key => & $value) {
239
                if ($key > $deleted) {
240
                    $formData['answers'][$key - 1] = $formData['answers'][$key];
241
                    unset($formData['answers'][$key]);
242
                }
243
            }
244
        }
245
246
        // Adding an answer
247
        if (isset($_POST['buttons']) && isset($_POST['buttons']['add_answer'])) {
248
            $counter++;
249
            Session::write('answer_count', $counter);
250
        }
251
252
        // Removing an answer
253
        if (isset($_POST['buttons']) && isset($_POST['buttons']['remove_answer'])) {
254
            $counter--;
255
            Session::write('answer_count', $counter);
256
            foreach ($formData['answers'] as $index => &$data) {
257
                if ($index > $counter) {
258
                    unset($formData['answers'][$index]);
259
                }
260
            }
261
        }
262
263
        if (!isset($_POST['delete_answer'])) {
264
            if (isset($formData['answers'])) {
265
                foreach ($formData['answers'] as $index => $data) {
266
                    if ($index > $counter) {
267
                        unset($formData['answers'][$index]);
268
                    }
269
                }
270
271
                for ($i = 0; $i <= $counter; $i++) {
272
                    if (!isset($formData['answers'][$i])) {
273
                        $formData['answers'][$i] = '';
274
                    }
275
                }
276
            }
277
        }
278
279
        $formData['answers'] = isset($formData['answers']) ? $formData['answers'] : [];
280
        Session::write('answer_list', $formData['answers']);
281
282
        return $formData;
283
    }
284
285
    /**
286
     * @param array $surveyData
287
     * @param array $formData
288
     *
289
     * @return mixed
290
     */
291
    public function save($surveyData, $formData)
292
    {
293
        // Saving a question
294
        if (isset($_POST['buttons']) && isset($_POST['buttons']['save'])) {
295
            Session::erase('answer_count');
296
            Session::erase('answer_list');
297
            $message = SurveyManager::save_question(
298
                $surveyData,
299
                $formData
300
            );
301
302
            if ($message == 'QuestionAdded' || $message == 'QuestionUpdated') {
303
                header('Location: '.api_get_path(WEB_CODE_PATH).'survey/survey.php?survey_id='.intval($_GET['survey_id']).'&message='.$message.'&'.api_get_cidreq());
304
                exit;
0 ignored issues
show
Best Practice introduced by
Using exit here is not recommended.

In general, usage of exit should be done with care and only when running in a scripting context like a CLI script.

Loading history...
305
            }
306
        }
307
308
        return $formData;
309
    }
310
311
    /**
312
     * Adds two buttons. One to add an option, one to remove an option
313
     *
314
     * @param array $data
315
     *
316
     */
317
    public function addRemoveButtons($data)
318
    {
319
        $this->buttonList['remove_answer'] = $this->getForm()->createElement(
320
            'button',
321
            'remove_answer',
322
            get_lang('RemoveAnswer'),
323
            'minus',
324
            'default'
325
        );
326
327
        if (count($data['answers']) <= 2) {
328
            $this->buttonList['remove_answer']->updateAttributes(
329
                array('disabled' => 'disabled')
330
            );
331
        }
332
333
        $this->buttonList['add_answer'] = $this->getForm()->createElement(
334
            'button',
335
            'add_answer',
336
            get_lang('AddAnswer'),
337
            'plus',
338
            'default'
339
        );
340
    }
341
342
    /**
343
     * @param FormValidator $form
344
     * @param array $questionData
345
     * @param array $answers
346
     */
347
    public function render(FormValidator $form, $questionData = array(), $answers = array())
0 ignored issues
show
Unused Code introduced by
The parameter $questionData is not used and could be removed. ( Ignorable by Annotation )

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

347
    public function render(FormValidator $form, /** @scrutinizer ignore-unused */ $questionData = array(), $answers = array())

This check looks for parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
Unused Code introduced by
The parameter $answers is not used and could be removed. ( Ignorable by Annotation )

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

347
    public function render(FormValidator $form, $questionData = array(), /** @scrutinizer ignore-unused */ $answers = array())

This check looks for parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
348
    {
349
        return null;
350
    }
351
}
352
353