CatForm::build_basic_form()   F
last analyzed

Complexity

Conditions 31
Paths > 20000

Size

Total Lines 219
Code Lines 140

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 31
eloc 140
nc 134784
nop 0
dl 0
loc 219
rs 0
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
3
/* For licensing terms, see /license.txt */
4
5
use Chamilo\CourseBundle\Entity\CDocument;
6
7
/**
8
 * @author Stijn Konings
9
 */
10
class CatForm extends FormValidator
11
{
12
    public const TYPE_ADD = 1;
13
    public const TYPE_EDIT = 2;
14
    public const TYPE_MOVE = 3;
15
    public const TYPE_SELECT_COURSE = 4;
16
17
    /** @var Category */
18
    private $category_object;
19
20
    /**
21
     * CatForm constructor.
22
     * Builds a form containing form items based on a given parameter.
23
     *
24
     * @param string $form_type       1=add, 2=edit,3=move,4=browse
25
     * @param string $category_object
26
     * @param string $form_name
27
     * @param string $method
28
     * @param null   $action
0 ignored issues
show
Documentation Bug introduced by
Are you sure the doc-type for parameter $action is correct as it would always require null to be passed?
Loading history...
29
     */
30
    public function __construct(
31
        $form_type,
32
        $category_object,
33
        $form_name,
34
        $method = 'post',
35
        $action = null
36
    ) {
37
        parent::__construct($form_name, $method, $action);
38
        $this->form_type = $form_type;
39
        if (isset($category_object)) {
40
            $this->category_object = $category_object;
0 ignored issues
show
Documentation Bug introduced by
It seems like $category_object of type string is incompatible with the declared type Category of property $category_object.

Our type inference engine has found an assignment to a property that is incompatible with the declared type of that property.

Either this assignment is in error or the assigned type should be added to the documentation/type hint for that property..

Loading history...
41
        }
42
43
        switch ($this->form_type) {
44
            case self::TYPE_EDIT:
45
                $this->build_editing_form();
46
                break;
47
            case self::TYPE_ADD:
48
                $this->build_add_form();
49
                break;
50
            case self::TYPE_MOVE:
51
                $this->build_move_form();
52
                break;
53
            case self::TYPE_SELECT_COURSE:
54
                $this->build_select_course_form();
55
                break;
56
        }
57
58
        $this->setDefaults();
59
    }
60
61
    /**
62
     * This function will build a move form that will allow the user to move a category to
63
     * a another.
64
     */
65
    protected function build_move_form()
66
    {
67
        $renderer = &$this->defaultRenderer();
68
        $renderer->setCustomElementTemplate('<span>{element}</span> ');
69
        $this->addElement(
70
            'static',
71
            null,
72
            null,
73
            '"'.$this->category_object->get_name().'" '
74
        );
75
        $this->addElement('static', null, null, get_lang('Move to').' : ');
76
        $select = $this->addSelect('move_cat', null);
77
        $line = null;
78
        foreach ($this->category_object->get_target_categories() as $cat) {
79
            for ($i = 0; $i < $cat[2]; $i++) {
80
                $line .= '--';
81
            }
82
            if ($cat[0] != $this->category_object->get_parent_id()) {
83
                $select->addOption($line.' '.$cat[1], $cat[0]);
84
            } else {
85
                $select->addOption($line.' '.$cat[1], $cat[0], 'disabled');
86
            }
87
            $line = '';
88
        }
89
        $this->addButtonSave(get_lang('Validate'));
90
    }
91
92
    /**
93
     * This function builds an 'add category form, if parent id is 0, it will only
94
     * show courses.
95
     */
96
    protected function build_add_form()
97
    {
98
        // check if we are a root category
99
        // if so, you can only choose between courses
100
        if ('0' == $this->category_object->get_parent_id()) {
101
            $this->setDefaults(
102
                [
103
                    'select_course' => $this->category_object->get_course_code(),
104
                    'hid_user_id' => $this->category_object->get_user_id(),
105
                    'hid_parent_id' => $this->category_object->get_parent_id(),
106
                ]
107
            );
108
        } else {
109
            $this->setDefaults(
110
                [
111
                    'hid_user_id' => $this->category_object->get_user_id(),
112
                    'hid_parent_id' => $this->category_object->get_parent_id(),
113
                ]
114
            );
115
            $this->addElement(
116
                'hidden',
117
                'course_code',
118
                $this->category_object->get_course_code()
119
            );
120
            $this->addElement(
121
                'hidden',
122
                'course_id',
123
                $this->category_object->getCourseId()
124
            );
125
        }
126
        $this->build_basic_form();
127
    }
128
129
    /**
130
     * Builds an form to edit a category.
131
     */
132
    protected function build_editing_form()
133
    {
134
        $skills = $this->category_object->getSkillsForSelect();
135
136
        $course_code = api_get_course_id();
137
        $session_id = api_get_session_id();
138
139
        $test_cats = Category::load(
140
            null,
141
            null,
142
            api_get_course_int_id(),
143
            null,
144
            null,
145
            $session_id,
146
            null
147
        );
148
149
        $links = null;
150
        if (isset($test_cats[0])) {
151
            $links = $test_cats[0]->get_links();
152
        }
153
        $grade_model_id = $this->category_object->get_grade_model_id();
154
155
        if (empty($links)) {
156
            $grade_model_id = 0;
157
        }
158
159
        $category_name = $this->category_object->get_name();
160
161
        // The main course category:
162
        if (!empty($this->category_object) && 0 == $this->category_object->get_parent_id()) {
163
            if (empty($category_name)) {
164
                $category_name = $course_code;
165
            }
166
        }
167
168
        $this->setDefaults(
169
            [
170
                'name' => $category_name,
171
                'description' => $this->category_object->get_description(),
172
                'hid_user_id' => $this->category_object->get_user_id(),
173
                'hid_parent_id' => $this->category_object->get_parent_id(),
174
                'grade_model_id' => $grade_model_id,
175
                'skills' => $skills,
176
                'weight' => $this->category_object->get_weight(),
177
                'visible' => $this->category_object->is_visible(),
178
                'certif_min_score' => $this->category_object->getCertificateMinScore(),
179
                'generate_certificates' => $this->category_object->getGenerateCertificates(),
180
                'is_requirement' => $this->category_object->getIsRequirement(),
181
            ]
182
        );
183
184
        $this->addElement('hidden', 'hid_id', $this->category_object->get_id());
185
        $this->addElement(
186
            'hidden',
187
            'course_code',
188
            $this->category_object->get_course_code()
189
        );
190
        $this->addElement(
191
            'hidden',
192
            'course_id',
193
            $this->category_object->getCourseId()
194
        );
195
        $this->build_basic_form();
196
    }
197
198
    /**
199
     * This function builds an 'select course' form in the add category process,
200
     * if parent id is 0, it will only show courses.
201
     */
202
    protected function build_select_course_form()
203
    {
204
        $select = $this->addSelect(
205
            'select_course',
206
            [get_lang('Pick a course'), 'test'],
207
            null
208
        );
209
        $courses = Category::get_all_courses(api_get_user_id());
210
        //only return courses that are not yet created by the teacher
211
        foreach ($courses as $row) {
212
            $select->addOption($row[1], $row[0]);
213
        }
214
        $this->setDefaults([
215
            'hid_user_id' => $this->category_object->get_user_id(),
216
            'hid_parent_id' => $this->category_object->get_parent_id(),
217
        ]);
218
        $this->addElement('hidden', 'hid_user_id');
219
        $this->addElement('hidden', 'hid_parent_id');
220
        $this->addButtonSave(get_lang('Validate'));
221
    }
222
223
    private function build_basic_form()
224
    {
225
        $this->addText(
226
            'name',
227
            get_lang('Category name'),
228
            true,
229
            ['maxlength' => '50']
230
        );
231
        $this->addRule('name', get_lang('Required field'), 'required');
232
233
        if (!empty($this->category_object) && 0 == $this->category_object->get_parent_id()) {
234
            // we can't change the root category
235
            $this->freeze('name');
236
        }
237
238
        $global_weight = api_get_setting('gradebook_default_weight');
239
240
        $value = 100;
241
        if (isset($global_weight)) {
242
            $value = $global_weight;
243
        }
244
245
        $this->addFloat(
246
            'weight',
247
            [
248
                get_lang('Total weight'),
249
                get_lang('The sum of all weights of activities inside this assessment has to be equivalent to this number.'),
250
            ],
251
            true,
252
            ['value' => $value, 'maxlength' => '5']
253
        );
254
255
        $skillsDefaults = [];
256
257
        $allowSkillEdit = api_is_platform_admin() || api_is_drh();
258
        if ('true' === api_get_setting('skill.skills_teachers_can_assign_skills')) {
259
            $allowSkillEdit = $allowSkillEdit || api_is_allowed_to_edit();
260
        }
261
262
        if ($allowSkillEdit) {
263
            if (SkillModel::isToolAvailable()) {
264
                $skillSelect = $this->addSelectAjax(
265
                    'skills',
266
                    [
267
                        get_lang('Skills'),
268
                        get_lang('Skills obtained when achieving this assessment'),
269
                    ],
270
                    [],
271
                    [
272
                        'id' => 'skills',
273
                        'multiple' => 'multiple',
274
                        'url' => api_get_path(WEB_AJAX_PATH).'skill.ajax.php?a=search_skills',
275
                    ]
276
                );
277
278
                // The magic should be here
279
                $skills = $this->category_object->get_skills();
280
                foreach ($skills as $skill) {
281
                    $skillsDefaults[] = $skill['id'];
282
                    $skillSelect->addOption($skill['name'], $skill['id']);
283
                }
284
            }
285
        }
286
287
        $defaultCertification = 0;
288
        if (!empty($this->category_object)) {
289
            $defaultCertification = $this->category_object->getCertificateMinScore();
290
        }
291
292
        if (!empty($this->category_object) &&
293
            0 == $this->category_object->get_parent_id()
294
        ) {
295
            $model = ExerciseLib::getCourseScoreModel();
296
            if (empty($model)) {
297
                $this->addText(
298
                    'certif_min_score',
299
                    get_lang('Minimum certification score'),
300
                    true,
301
                    ['maxlength' => '5']
302
                );
303
            } else {
304
                $questionWeighting = $value;
305
                $defaultCertification = api_number_format($this->category_object->getCertificateMinScore(), 2);
306
                $select = $this->addSelect(
307
                    'certif_min_score',
308
                    get_lang('Minimum certification score'),
309
                    [],
310
                    ['disable_js' => true]
311
                );
312
313
                foreach ($model['score_list'] as $item) {
314
                    $i = api_number_format($item['score_to_qualify'] / 100 * $questionWeighting, 2);
315
                    $model = ExerciseLib::getModelStyle($item, $i);
316
                    $attributes = ['class' => $item['css_class']];
317
                    if ($defaultCertification == $i) {
318
                        $attributes['selected'] = 'selected';
319
                    }
320
                    $select->addOption($model, $i, $attributes);
321
                }
322
                $select->updateSelectWithSelectedOption($this);
323
            }
324
325
            $this->addRule(
326
                'certif_min_score',
327
                get_lang('Only numbers'),
328
                'numeric'
329
            );
330
            $this->addRule(
331
                'certif_min_score',
332
                get_lang('Negative value'),
333
                'compare',
334
                '>=',
335
                'server',
336
                false,
337
                false,
338
                0
339
            );
340
        } else {
341
            $this->addElement('checkbox', 'visible', null, get_lang('Visible'));
342
        }
343
344
        $this->addElement('hidden', 'hid_user_id');
345
        $this->addElement('hidden', 'hid_parent_id');
346
        $this->addElement(
347
            'textarea',
348
            'description',
349
            get_lang('Description')
350
        );
351
352
        if (!empty($this->category_object) &&
353
            0 == $this->category_object->get_parent_id() &&
354
            (api_is_platform_admin() || 'true' === api_get_setting('teachers_can_change_grade_model_settings'))
355
        ) {
356
            // Getting grade models
357
            $obj = new GradeModel();
358
            $obj->fill_grade_model_select_in_form(
359
                $this,
360
                'grade_model_id',
361
                $this->category_object->get_grade_model_id()
362
            );
363
364
            // Freeze or not
365
            $session_id = api_get_session_id();
366
            $test_cats = Category::load(
367
                null,
368
                null,
369
                api_get_course_int_id(),
370
                null,
371
                null,
372
                $session_id,
373
                null
374
            );
375
            $links = null;
376
            if (!empty($test_cats[0])) {
377
                $links = $test_cats[0]->get_links();
378
            }
379
380
            if (count($test_cats) > 1 || !empty($links)) {
381
                if ('true' === api_get_setting('gradebook_enable_grade_model')) {
382
                    $this->freeze('grade_model_id');
383
                }
384
            }
385
386
            $generateCertificatesParams = [];
387
            if ($this->category_object->getGenerateCertificates()) {
388
                $generateCertificatesParams['checked'] = 'checked';
389
            }
390
391
            $this->addElement(
392
                'checkbox',
393
                'generate_certificates',
394
                null,
395
                get_lang('Generate certificates'),
396
                $generateCertificatesParams
397
            );
398
        }
399
400
        $isRequirementCheckbox = $this->addCheckBox(
401
            'is_requirement',
402
            [
403
                null,
404
                get_lang('Consider this gradebook as a requirement to complete the course (influences the sessions sequences)'),
405
            ],
406
            get_lang('Is requirement')
407
        );
408
409
        if ($this->category_object->getIsRequirement()) {
410
            $isRequirementCheckbox->setChecked(true);
411
        }
412
413
        $documentId = $this->category_object->getDocumentId();
414
        if (!empty($documentId)) {
415
            $repo = \Chamilo\CoreBundle\Framework\Container::getDocumentRepository();
416
            /** @var CDocument $documentData */
417
            $documentData = $repo->find($documentId);
418
419
            if (!empty($documentData)) {
420
                $this->addLabel(get_lang('Certificate'), $documentData->getTitle());
421
            }
422
        }
423
424
        if (self::TYPE_ADD == $this->form_type) {
425
            $this->addButtonCreate(get_lang('Add category'));
426
        } else {
427
            $this->addElement('hidden', 'editcat', (int) $_GET['editcat']);
428
            $this->addButtonUpdate(get_lang('Edit this category'));
429
        }
430
431
        $setting = api_get_setting('tool_visible_by_default_at_creation');
432
        $visibility_default = 1;
433
        if (isset($setting['gradebook']) && 'false' === $setting['gradebook']) {
434
            $visibility_default = 0;
435
        }
436
437
        $this->setDefaults(
438
            [
439
                'visible' => $visibility_default,
440
                'skills' => $skillsDefaults,
441
                'certif_min_score' => (string) $defaultCertification,
442
            ]
443
        );
444
    }
445
}
446