Passed
Push — master ( ccb5fd...57fe34 )
by Julito
13:03
created

CatForm::setDefaults()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 1
nc 1
nop 2
dl 0
loc 3
rs 10
c 0
b 0
f 0
1
<?php
2
/* For licensing terms, see /license.txt */
3
4
/**
5
 * Class CatForm.
6
 *
7
 * @author Stijn Konings
8
 *
9
 * @package chamilo.gradebook
10
 */
11
class CatForm extends FormValidator
12
{
13
    const TYPE_ADD = 1;
14
    const TYPE_EDIT = 2;
15
    const TYPE_MOVE = 3;
16
    const TYPE_SELECT_COURSE = 4;
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;
0 ignored issues
show
Bug Best Practice introduced by
The property form_type does not exist. Although not strictly required by PHP, it is generally a best practice to declare properties explicitly.
Loading history...
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('MoveTo').' : ');
76
        $select = $this->addElement('select', 'move_cat', null, 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->addElement('submit', null, get_lang('Ok'));
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 ($this->category_object->get_parent_id() == '0') {
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
        }
121
        $this->build_basic_form();
122
    }
123
124
    /**
125
     * Builds an form to edit a category.
126
     */
127
    protected function build_editing_form()
128
    {
129
        $skills = $this->category_object->getSkillsForSelect();
130
131
        $course_code = api_get_course_id();
132
        $session_id = api_get_session_id();
133
134
        $test_cats = Category::load(
135
            null,
136
            null,
137
            $course_code,
138
            null,
139
            null,
140
            $session_id,
141
            false
142
        );
143
144
        $links = null;
145
        if (isset($test_cats[0])) {
146
            $links = $test_cats[0]->get_links();
147
        }
148
        $grade_model_id = $this->category_object->get_grade_model_id();
149
150
        if (empty($links)) {
151
            $grade_model_id = 0;
152
        }
153
154
        $category_name = $this->category_object->get_name();
155
156
        // The main course category:
157
        if (isset($this->category_object) && $this->category_object->get_parent_id() == 0) {
158
            if (empty($category_name)) {
159
                $category_name = $course_code;
160
            }
161
        }
162
163
        $this->setDefaults(
164
            [
165
                'name' => $category_name,
166
                'description' => $this->category_object->get_description(),
167
                'hid_user_id' => $this->category_object->get_user_id(),
168
                'hid_parent_id' => $this->category_object->get_parent_id(),
169
                'grade_model_id' => $grade_model_id,
170
                'skills' => $skills,
171
                'weight' => $this->category_object->get_weight(),
172
                'visible' => $this->category_object->is_visible(),
173
                'certif_min_score' => $this->category_object->getCertificateMinScore(),
174
                'generate_certificates' => $this->category_object->getGenerateCertificates(),
175
                'is_requirement' => $this->category_object->getIsRequirement(),
176
            ]
177
        );
178
179
        $this->addElement('hidden', 'hid_id', $this->category_object->get_id());
180
        $this->addElement(
181
            'hidden',
182
            'course_code',
183
            $this->category_object->get_course_code()
184
        );
185
        $this->build_basic_form();
186
    }
187
188
    /**
189
     * This function builds an 'select course' form in the add category process,
190
     * if parent id is 0, it will only show courses.
191
     */
192
    protected function build_select_course_form()
193
    {
194
        $select = $this->addElement(
195
            'select',
196
            'select_course',
197
            [get_lang('PickACourse'), 'test'],
198
            null
199
        );
200
        $courses = Category::get_all_courses(api_get_user_id());
201
        //only return courses that are not yet created by the teacher
202
        foreach ($courses as $row) {
203
            $select->addoption($row[1], $row[0]);
204
        }
205
        $this->setDefaults([
206
            'hid_user_id' => $this->category_object->get_user_id(),
207
            'hid_parent_id' => $this->category_object->get_parent_id(),
208
        ]);
209
        $this->addElement('hidden', 'hid_user_id');
210
        $this->addElement('hidden', 'hid_parent_id');
211
        $this->addElement('submit', null, get_lang('Ok'));
212
    }
213
214
    private function build_basic_form()
215
    {
216
        $this->addText(
217
            'name',
218
            get_lang('CategoryName'),
219
            true,
220
            ['maxlength' => '50']
221
        );
222
        $this->addRule('name', get_lang('ThisFieldIsRequired'), 'required');
223
224
        if (isset($this->category_object) &&
225
            $this->category_object->get_parent_id() == 0
226
        ) {
227
            // we can't change the root category
228
            $this->freeze('name');
229
        }
230
231
        $global_weight = api_get_setting('gradebook_default_weight');
232
233
        $value = 100;
234
        if (isset($global_weight)) {
235
            $value = $global_weight;
236
        }
237
238
        $this->addFloat(
239
            'weight',
240
            [
241
                get_lang('TotalWeight'),
242
                get_lang('TotalSumOfWeights'),
243
            ],
244
            true,
245
            ['value' => $value, 'maxlength' => '5']
246
        );
247
248
        $skillsDefaults = [];
249
        if (api_is_platform_admin() || api_is_drh()) {
250
            if (Skill::isToolAvailable()) {
251
                $skillSelect = $this->addElement(
252
                    'select_ajax',
253
                    'skills',
254
                    [
255
                        get_lang('Skills'),
256
                        get_lang('SkillsAchievedWhenAchievingThisGradebook'),
257
                    ],
258
                    null,
259
                    [
260
                        'id' => 'skills',
261
                        'multiple' => 'multiple',
262
                        'url' => api_get_path(WEB_AJAX_PATH).'skill.ajax.php?a=search_skills',
263
                    ]
264
                );
265
266
                // The magic should be here
267
                $skills = $this->category_object->get_skills();
268
                foreach ($skills as $skill) {
269
                    $skillsDefaults[] = $skill['id'];
270
                    $skillSelect->addOption($skill['name'], $skill['id']);
271
                }
272
            }
273
        }
274
275
        $defaultCertification = 0;
276
        if (isset($this->category_object) &&
277
            $this->category_object->get_parent_id() == 0
278
        ) {
279
            $model = ExerciseLib::getCourseScoreModel();
280
            if (empty($model)) {
281
                $this->addText(
282
                    'certif_min_score',
283
                    get_lang('CertificateMinScore'),
284
                    true,
285
                    ['maxlength' => '5']
286
                );
287
            } else {
288
                $questionWeighting = $value;
289
                $defaultCertification = api_number_format($this->category_object->getCertificateMinScore(), 2);
290
                $select = $this->addSelect(
291
                    'certif_min_score',
292
                    get_lang('CertificateMinScore'),
293
                    [],
294
                    ['disable_js' => true]
295
                );
296
297
                foreach ($model['score_list'] as $item) {
298
                    $i = api_number_format($item['score_to_qualify'] / 100 * $questionWeighting, 2);
299
                    $model = ExerciseLib::getModelStyle($item, $i);
300
                    $attributes = ['class' => $item['css_class']];
301
                    if ($defaultCertification == $i) {
302
                        $attributes['selected'] = 'selected';
303
                    }
304
                    $select->addOption($model, $i, $attributes);
305
                }
306
                $select->updateSelectWithSelectedOption($this);
307
            }
308
309
            $this->addRule(
310
                'certif_min_score',
311
                get_lang('OnlyNumbers'),
312
                'numeric'
313
            );
314
            $this->addRule(
315
                'certif_min_score',
316
                get_lang('NegativeValue'),
317
                'compare',
318
                '>=',
319
                'server',
320
                false,
321
                false,
322
                0
323
            );
324
        } else {
325
            $this->addElement('checkbox', 'visible', null, get_lang('Visible'));
326
        }
327
328
        $this->addElement('hidden', 'hid_user_id');
329
        $this->addElement('hidden', 'hid_parent_id');
330
        $this->addElement(
331
            'textarea',
332
            'description',
333
            get_lang('Description')
334
        );
335
336
        if (isset($this->category_object) &&
337
            $this->category_object->get_parent_id() == 0 &&
338
            (api_is_platform_admin() || api_get_setting('teachers_can_change_grade_model_settings') == 'true')
339
        ) {
340
            // Getting grade models
341
            $obj = new GradeModel();
342
            $obj->fill_grade_model_select_in_form(
343
                $this,
344
                'grade_model_id',
345
                $this->category_object->get_grade_model_id()
0 ignored issues
show
Bug introduced by
It seems like $this->category_object->get_grade_model_id() can also be of type integer; however, parameter $default_value of GradeModel::fill_grade_model_select_in_form() does only seem to accept null, 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

345
                /** @scrutinizer ignore-type */ $this->category_object->get_grade_model_id()
Loading history...
346
            );
347
348
            // Freeze or not
349
            $course_code = api_get_course_id();
350
            $session_id = api_get_session_id();
351
            $test_cats = Category::load(
352
                null,
353
                null,
354
                $course_code,
355
                null,
356
                null,
357
                $session_id,
358
                false
359
            );
360
            $links = null;
361
            if (!empty($test_cats[0])) {
362
                $links = $test_cats[0]->get_links();
363
            }
364
365
            if (count($test_cats) > 1 || !empty($links)) {
366
                if (api_get_setting('gradebook_enable_grade_model') == 'true') {
367
                    $this->freeze('grade_model_id');
368
                }
369
            }
370
371
            $generateCertificatesParams = [];
372
            if ($this->category_object->getGenerateCertificates()) {
373
                $generateCertificatesParams['checked'] = 'checked';
374
            }
375
376
            $this->addElement(
377
                'checkbox',
378
                'generate_certificates',
379
                null,
380
                get_lang('GenerateCertificates'),
381
                $generateCertificatesParams
382
            );
383
        }
384
385
        if (!empty($session_id)) {
386
            $isRequirementCheckbox = $this->addCheckBox(
387
                'is_requirement',
388
                [
389
                    null,
390
                    get_lang('ConsiderThisGradebookAsRequirementForASessionSequence'),
391
                ],
392
                get_lang('IsRequirement')
393
            );
394
        }
395
396
        if ($this->category_object->getIsRequirement()) {
397
            $isRequirementCheckbox->setChecked(true);
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $isRequirementCheckbox does not seem to be defined for all execution paths leading up to this point.
Loading history...
398
        }
399
400
        $documentId = $this->category_object->getDocumentId();
401
        if (!empty($documentId)) {
402
            $documentData = DocumentManager::get_document_data_by_id($documentId, api_get_course_id());
403
404
            if (!empty($documentData)) {
405
                $this->addLabel(get_lang('Certificate'), $documentData['title']);
406
            }
407
        }
408
409
        if ($this->form_type == self::TYPE_ADD) {
410
            $this->addButtonCreate(get_lang('AddCategory'));
411
        } else {
412
            $this->addElement('hidden', 'editcat', intval($_GET['editcat']));
413
            $this->addButtonUpdate(get_lang('EditCategory'));
414
        }
415
416
        $setting = api_get_setting('tool_visible_by_default_at_creation');
417
        $visibility_default = 1;
418
        if (isset($setting['gradebook']) && $setting['gradebook'] == 'false') {
419
            $visibility_default = 0;
420
        }
421
422
        $this->setDefaults(
423
            [
424
                'visible' => $visibility_default,
425
                'skills' => $skillsDefaults,
426
                'certif_min_score' => (string) $defaultCertification,
427
            ]
428
        );
429
    }
430
}
431