Passed
Push — 1.11.x ( f8e160...2aa0a6 )
by Julito
09:51
created

ScoreDisplay::updateCustomScoreDisplaySettings()   A

Complexity

Conditions 3
Paths 4

Size

Total Lines 27
Code Lines 16

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 3
eloc 16
nc 4
nop 3
dl 0
loc 27
rs 9.7333
c 0
b 0
f 0
1
<?php
2
3
/* For licensing terms, see /license.txt */
4
5
/**
6
 * Class ScoreDisplay
7
 * Display scores according to the settings made by the platform admin.
8
 * This class works as a singleton: call instance() to retrieve an object.
9
 *
10
 * @author Bert Steppé
11
 */
12
class ScoreDisplay
13
{
14
    private $coloring_enabled;
15
    private $color_split_value;
16
    private $custom_enabled;
17
    private $upperlimit_included;
18
    private $custom_display;
19
    private $custom_display_conv;
20
21
    /**
22
     * Protected constructor - call instance() to instantiate.
23
     *
24
     * @param int $category_id
25
     */
26
    public function __construct($category_id = 0)
27
    {
28
        if (!empty($category_id)) {
29
            $this->category_id = $category_id;
0 ignored issues
show
Bug Best Practice introduced by
The property category_id does not exist. Although not strictly required by PHP, it is generally a best practice to declare properties explicitly.
Loading history...
30
        }
31
32
        // Loading portal settings + using standard functions.
33
        $value = api_get_setting('gradebook_score_display_coloring');
34
        $value = $value['my_display_coloring'];
35
36
        // Setting coloring.
37
        $this->coloring_enabled = $value === 'true' ? true : false;
38
39
        if ($this->coloring_enabled) {
40
            $value = api_get_setting('gradebook_score_display_colorsplit');
41
            if (isset($value)) {
42
                $this->color_split_value = $value;
43
            }
44
        }
45
46
        // Setting custom enabled
47
        $value = api_get_setting('gradebook_score_display_custom');
48
        $value = $value['my_display_custom'];
49
        $this->custom_enabled = $value === 'true' ? true : false;
50
51
        if ($this->custom_enabled) {
52
            $params = ['category = ?' => ['Gradebook']];
53
            $displays = api_get_settings_params($params);
54
            $portal_displays = [];
55
            if (!empty($displays)) {
56
                foreach ($displays as $display) {
57
                    $data = explode('::', $display['selected_value']);
58
                    if (empty($data[1])) {
59
                        $data[1] = '';
60
                    }
61
                    $portal_displays[$data[0]] = [
62
                        'score' => $data[0],
63
                        'display' => $data[1],
64
                    ];
65
                }
66
                sort($portal_displays);
67
            }
68
            $this->custom_display = $portal_displays;
69
            if (count($this->custom_display) > 0) {
70
                $value = api_get_setting('gradebook_score_display_upperlimit');
71
                $value = $value['my_display_upperlimit'];
72
                $this->upperlimit_included = $value === 'true' ? true : false;
73
                $this->custom_display_conv = $this->convert_displays($this->custom_display);
74
            }
75
        }
76
77
        // If teachers can override the portal parameters
78
        if (api_get_setting('teachers_can_change_score_settings') === 'true') {
79
            //Load course settings
80
            if ($this->custom_enabled) {
81
                $this->custom_display = $this->get_custom_displays();
82
                if (count($this->custom_display) > 0) {
83
                    $this->custom_display_conv = $this->convert_displays($this->custom_display);
84
                }
85
            }
86
87
            if ($this->coloring_enabled) {
88
                $this->color_split_value = $this->get_score_color_percent();
89
            }
90
        }
91
    }
92
93
    /**
94
     * Get the instance of this class.
95
     *
96
     * @param int $categoryId
97
     *
98
     * @return ScoreDisplay
99
     */
100
    public static function instance($categoryId = 0)
101
    {
102
        static $instance;
103
        if (!isset($instance)) {
104
            $instance = new ScoreDisplay($categoryId);
105
        }
106
107
        return $instance;
108
    }
109
110
    /**
111
     * Compare the custom display of 2 scores, can be useful in sorting.
112
     */
113
    public static function compare_scores_by_custom_display($score1, $score2)
114
    {
115
        if (!isset($score1)) {
116
            return isset($score2) ? 1 : 0;
117
        }
118
119
        if (!isset($score2)) {
120
            return -1;
121
        }
122
123
        $scoreDisplay = self::instance();
124
        $custom1 = $scoreDisplay->display_custom($score1);
125
        $custom2 = $scoreDisplay->display_custom($score2);
126
        if ($custom1 == $custom2) {
127
            return 0;
128
        }
129
130
        return ($score1[0] / $score1[1]) < ($score2[0] / $score2[1]) ? -1 : 1;
131
    }
132
133
    /**
134
     * Is coloring enabled ?
135
     */
136
    public function is_coloring_enabled()
137
    {
138
        return $this->coloring_enabled;
139
    }
140
141
    /**
142
     * Is custom score display enabled ?
143
     */
144
    public function is_custom()
145
    {
146
        return $this->custom_enabled;
147
    }
148
149
    /**
150
     * Is upperlimit included ?
151
     */
152
    public function is_upperlimit_included()
153
    {
154
        return $this->upperlimit_included;
155
    }
156
157
    /**
158
     * If custom score display is enabled, this will return the current settings.
159
     * See also updateCustomScoreDisplaySettings.
160
     *
161
     * @return array current settings (or null if feature not enabled)
162
     */
163
    public function get_custom_score_display_settings()
164
    {
165
        return $this->custom_display;
166
    }
167
168
    /**
169
     * If coloring is enabled, scores below this value will be displayed in red.
170
     *
171
     * @return int color split value, in percent (or null if feature not enabled)
172
     */
173
    public function get_color_split_value()
174
    {
175
        return $this->color_split_value;
176
    }
177
178
    /**
179
     * Update custom score display settings.
180
     *
181
     * @param array $displays 2-dimensional array - every sub array must have keys (score, display)
182
     * @param int   score color percent (optional)
183
     * @param int   gradebook category id (optional)
184
     */
185
    public function updateCustomScoreDisplaySettings(
186
        $displays,
187
        $scorecolpercent = 0,
188
        $category_id = null
189
    ) {
190
        $this->custom_display = $displays;
191
        $this->custom_display_conv = $this->convert_displays($this->custom_display);
192
        if (isset($category_id)) {
193
            $category_id = (int) $category_id;
194
        } else {
195
            $category_id = $this->get_current_gradebook_category_id();
196
        }
197
198
        // remove previous settings
199
        $table = Database::get_main_table(TABLE_MAIN_GRADEBOOK_SCORE_DISPLAY);
200
        $sql = 'DELETE FROM '.$table.' WHERE category_id = '.$category_id;
201
        Database::query($sql);
202
203
        // add new settings
204
        foreach ($displays as $display) {
205
            $params = [
206
                'score' => $display['score'],
207
                'display' => $display['display'],
208
                'category_id' => $category_id,
209
                'score_color_percent' => $scorecolpercent,
210
            ];
211
            Database::insert($table, $params);
212
        }
213
    }
214
215
    /**
216
     * @param int $category_id
217
     *
218
     * @return false|null
219
     */
220
    public function insert_defaults($category_id)
221
    {
222
        if (empty($category_id)) {
223
            return false;
224
        }
225
226
        //Get this from DB settings
227
        $display = [
228
            50 => get_lang('GradebookFailed'),
229
            60 => get_lang('GradebookPoor'),
230
            70 => get_lang('GradebookFair'),
231
            80 => get_lang('GradebookGood'),
232
            90 => get_lang('GradebookOutstanding'),
233
            100 => get_lang('GradebookExcellent'),
234
        ];
235
236
        $table = Database::get_main_table(TABLE_MAIN_GRADEBOOK_SCORE_DISPLAY);
237
        foreach ($display as $value => $text) {
238
            $params = [
239
                'score' => $value,
240
                'display' => $text,
241
                'category_id' => $category_id,
242
                'score_color_percent' => 0,
243
            ];
244
            Database::insert($table, $params);
245
        }
246
    }
247
248
    /**
249
     * @return int
250
     */
251
    public function get_number_decimals()
252
    {
253
        $number_decimals = api_get_setting('gradebook_number_decimals');
254
        if (!isset($number_decimals)) {
255
            $number_decimals = 0;
256
        }
257
258
        return $number_decimals;
0 ignored issues
show
Bug Best Practice introduced by
The expression return $number_decimals also could return the type string which is incompatible with the documented return type integer.
Loading history...
259
    }
260
261
    /**
262
     * Formats a number depending of the number of decimals.
263
     *
264
     * @param float  $score
265
     * @param bool   $ignoreDecimals
266
     * @param string $decimalSeparator
267
     * @param string $thousandSeparator
268
     *
269
     * @return float the score formatted
270
     */
271
    public function format_score($score, $ignoreDecimals = false, $decimalSeparator = '.', $thousandSeparator = ',')
272
    {
273
        $decimals = $this->get_number_decimals();
274
        if ($ignoreDecimals) {
275
            $decimals = 0;
276
        }
277
278
        return api_number_format($score, $decimals, $decimalSeparator, $thousandSeparator);
0 ignored issues
show
Bug Best Practice introduced by
The expression return api_number_format...or, $thousandSeparator) returns the type string which is incompatible with the documented return type double.
Loading history...
279
    }
280
281
    /**
282
     * Display a score according to the current settings.
283
     *
284
     * @param array $score          data structure, as returned by the calc_score functions
285
     * @param int   $type           one of the following constants:
286
     *                              SCORE_DIV, SCORE_PERCENT, SCORE_DIV_PERCENT, SCORE_AVERAGE
287
     *                              (ignored for student's view if custom score display is enabled)
288
     * @param int   $what           one of the following constants:
289
     *                              SCORE_BOTH, SCORE_ONLY_DEFAULT, SCORE_ONLY_CUSTOM (default: SCORE_BOTH)
290
     *                              (only taken into account if custom score display is enabled and for course/platform admin)
291
     * @param bool  $disableColor
292
     * @param bool  $ignoreDecimals
293
     *
294
     * @return string
295
     */
296
    public function display_score(
297
        $score,
298
        $type = SCORE_DIV_PERCENT,
299
        $what = SCORE_BOTH,
0 ignored issues
show
Unused Code introduced by
The parameter $what 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

299
        /** @scrutinizer ignore-unused */ $what = SCORE_BOTH,

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...
300
        $disableColor = false,
301
        $ignoreDecimals = false
302
    ) {
303
        $my_score = $score == 0 ? 1 : $score;
304
305
        if ($type == SCORE_BAR) {
306
            $percentage = $my_score[0] / $my_score[1] * 100;
307
308
            return Display::bar_progress($percentage);
309
        }
310
        if ($type == SCORE_NUMERIC) {
311
            $percentage = $my_score[0] / $my_score[1] * 100;
312
313
            return round($percentage);
314
        }
315
316
        if ($type == SCORE_SIMPLE) {
317
            $simpleScore = $this->format_score($my_score[0], $ignoreDecimals);
318
319
            return $simpleScore;
320
        }
321
322
        if ($this->custom_enabled && isset($this->custom_display_conv)) {
323
            $display = $this->display_default($my_score, $type, $ignoreDecimals);
324
        } else {
325
            // if no custom display set, use default display
326
            $display = $this->display_default($my_score, $type, $ignoreDecimals);
327
        }
328
        if ($this->coloring_enabled && $disableColor == false) {
0 ignored issues
show
Coding Style Best Practice introduced by
It seems like you are loosely comparing two booleans. Considering using the strict comparison === instead.

When comparing two booleans, it is generally considered safer to use the strict comparison operator.

Loading history...
329
            $my_score_denom = isset($score[1]) && !empty($score[1]) && $score[1] > 0 ? $score[1] : 1;
330
            $scoreCleaned = isset($score[0]) ? $score[0] : 0;
331
            if (($scoreCleaned / $my_score_denom) < ($this->color_split_value / 100)) {
332
                $display = Display::tag(
333
                    'font',
334
                    $display,
335
                    ['color' => 'red']
336
                );
337
            }
338
        }
339
340
        return $display;
341
    }
342
343
    /**
344
     * Get current gradebook category id.
345
     *
346
     * @return int Category id
347
     */
348
    private function get_current_gradebook_category_id()
349
    {
350
        $table = Database::get_main_table(TABLE_MAIN_GRADEBOOK_CATEGORY);
351
        $courseCode = api_get_course_id();
352
        $sessionId = api_get_session_id();
353
        $sessionCondition = api_get_session_condition($sessionId, true);
354
355
        $sql = "SELECT id FROM $table
356
                WHERE course_code = '$courseCode'  $sessionCondition";
357
        $rs = Database::query($sql);
358
        $categoryId = 0;
359
        if (Database::num_rows($rs) > 0) {
360
            $row = Database::fetch_row($rs);
361
            $categoryId = $row[0];
362
        }
363
364
        return $categoryId;
365
    }
366
367
    /**
368
     * @param $score
369
     * @param int  $type
370
     * @param bool $ignoreDecimals
371
     *
372
     * @return string
373
     */
374
    private function display_default($score, $type, $ignoreDecimals = false)
375
    {
376
        switch ($type) {
377
            case SCORE_DIV:                            // X / Y
378
                return $this->display_as_div($score, $ignoreDecimals);
379
            case SCORE_PERCENT:                        // XX %
380
                return $this->display_as_percent($score);
381
            case SCORE_DIV_PERCENT:                    // X / Y (XX %)
382
                return $this->display_as_div($score).' ('.$this->display_as_percent($score).')';
383
            case SCORE_AVERAGE:                        // XX %
384
                return $this->display_as_percent($score);
385
            case SCORE_DECIMAL:                        // 0.50  (X/Y)
386
                return $this->display_as_decimal($score);
387
            case SCORE_DIV_PERCENT_WITH_CUSTOM:        // X / Y (XX %) - Good!
388
                $custom = $this->display_custom($score);
389
                if (!empty($custom)) {
390
                    $custom = ' - '.$custom;
391
                }
392
393
                return $this->display_as_div($score).' ('.$this->display_as_percent($score).')'.$custom;
394
            case SCORE_DIV_SIMPLE_WITH_CUSTOM:         // X - Good!
395
                $custom = $this->display_custom($score);
396
397
                if (!empty($custom)) {
398
                    $custom = ' - '.$custom;
399
                }
400
401
                return $this->display_simple_score($score).$custom;
402
                break;
0 ignored issues
show
Unused Code introduced by
break is not strictly necessary here and could be removed.

The break statement is not necessary if it is preceded for example by a return statement:

switch ($x) {
    case 1:
        return 'foo';
        break; // This break is not necessary and can be left off.
}

If you would like to keep this construct to be consistent with other case statements, you can safely mark this issue as a false-positive.

Loading history...
403
            case SCORE_DIV_SIMPLE_WITH_CUSTOM_LETTERS:
404
                $custom = $this->display_custom($score);
405
                if (!empty($custom)) {
406
                    $custom = ' - '.$custom;
407
                }
408
                $score = $this->display_simple_score($score);
409
410
                //needs sudo apt-get install php5-intl
411
                if (class_exists('NumberFormatter')) {
412
                    $iso = api_get_language_isocode();
413
                    $f = new NumberFormatter($iso, NumberFormatter::SPELLOUT);
414
                    $letters = $f->format($score);
0 ignored issues
show
Bug introduced by
It seems like $score can also be of type string; however, parameter $value of NumberFormatter::format() does only seem to accept double|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

414
                    $letters = $f->format(/** @scrutinizer ignore-type */ $score);
Loading history...
415
                    $letters = api_strtoupper($letters);
416
                    $letters = " ($letters) ";
417
                }
418
419
                return $score.$letters.$custom;
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $letters does not seem to be defined for all execution paths leading up to this point.
Loading history...
420
                break;
421
            case SCORE_CUSTOM:                          // Good!
422
                return $this->display_custom($score);
423
        }
424
    }
425
426
    /**
427
     * @param array $score
428
     *
429
     * @return float|string
430
     */
431
    private function display_simple_score($score)
432
    {
433
        if (isset($score[0])) {
434
            return $this->format_score($score[0]);
435
        }
436
437
        return '';
438
    }
439
440
    /**
441
     * Returns "1" for array("100", "100");.
442
     *
443
     * @param array $score
444
     *
445
     * @return float
446
     */
447
    private function display_as_decimal($score)
448
    {
449
        $score_denom = ($score[1] == 0) ? 1 : $score[1];
450
451
        return $this->format_score($score[0] / $score_denom);
452
    }
453
454
    /**
455
     * Returns "100 %" for array("100", "100");.
456
     */
457
    private function display_as_percent($score)
458
    {
459
        $score_denom = ($score[1] == 0) ? 1 : $score[1];
460
461
        return $this->format_score($score[0] / $score_denom * 100).' %';
462
    }
463
464
    /**
465
     * Returns 10.00 / 10.00 for array("100", "100");.
466
     *
467
     * @param array $score
468
     * @param bool  $ignoreDecimals
469
     *
470
     * @return string
471
     */
472
    private function display_as_div($score, $ignoreDecimals = false)
473
    {
474
        if ($score == 1) {
475
            return '0 / 0';
476
        } else {
477
            $score[0] = isset($score[0]) ? $this->format_score($score[0], $ignoreDecimals) : 0;
478
            $score[1] = isset($score[1]) ? $this->format_score($score[1], $ignoreDecimals) : 0;
479
480
            return  $score[0].' / '.$score[1];
481
        }
482
    }
483
484
    /**
485
     * Depends on the teacher's configuration of thresholds. i.e. [0 50] "Bad", [50:100] "Good".
486
     *
487
     * @param array $score
488
     *
489
     * @return string
490
     */
491
    private function display_custom($score)
492
    {
493
        $my_score_denom = $score[1] == 0 ? 1 : $score[1];
494
        $scaledscore = $score[0] / $my_score_denom;
495
496
        if ($this->upperlimit_included) {
497
            foreach ($this->custom_display_conv as $displayitem) {
498
                if ($scaledscore <= $displayitem['score']) {
499
                    return $displayitem['display'];
500
                }
501
            }
502
        } else {
503
            if (!empty($this->custom_display_conv)) {
504
                foreach ($this->custom_display_conv as $displayitem) {
505
                    if ($scaledscore < $displayitem['score'] || $displayitem['score'] == 1) {
506
                        return $displayitem['display'];
507
                    }
508
                }
509
            }
510
        }
511
    }
512
513
    /**
514
     * Get score color percent by category.
515
     *
516
     * @param   int Gradebook category id
517
     *
518
     * @return int Score
519
     */
520
    private function get_score_color_percent($category_id = null)
521
    {
522
        $tbl_display = Database::get_main_table(TABLE_MAIN_GRADEBOOK_SCORE_DISPLAY);
523
        if (isset($category_id)) {
524
            $category_id = (int) $category_id;
525
        } else {
526
            $category_id = $this->get_current_gradebook_category_id();
527
        }
528
529
        $sql = 'SELECT score_color_percent FROM '.$tbl_display.'
530
                WHERE category_id = '.$category_id.'
531
                LIMIT 1';
532
        $result = Database::query($sql);
533
        $score = 0;
534
        if (Database::num_rows($result) > 0) {
535
            $row = Database::fetch_row($result);
536
            $score = $row[0];
537
        }
538
539
        return $score;
540
    }
541
542
    /**
543
     * Get current custom score display settings.
544
     *
545
     * @param   int     Gradebook category id
546
     *
547
     * @return array 2-dimensional array every element contains 3 subelements (id, score, display)
548
     */
549
    private function get_custom_displays($category_id = null)
550
    {
551
        $tbl_display = Database::get_main_table(TABLE_MAIN_GRADEBOOK_SCORE_DISPLAY);
552
        if (isset($category_id)) {
553
            $category_id = (int) $category_id;
554
        } else {
555
            $category_id = $this->get_current_gradebook_category_id();
556
        }
557
        $sql = 'SELECT * FROM '.$tbl_display.'
558
                WHERE category_id = '.$category_id.'
559
                ORDER BY score';
560
        $result = Database::query($sql);
561
562
        return Database::store_result($result, 'ASSOC');
563
    }
564
565
    /**
566
     * Convert display settings to internally used values.
567
     */
568
    private function convert_displays($custom_display)
569
    {
570
        if (isset($custom_display)) {
571
            // get highest score entry, and copy each element to a new array
572
            $converted = [];
573
            $highest = 0;
574
            foreach ($custom_display as $element) {
575
                if ($element['score'] > $highest) {
576
                    $highest = $element['score'];
577
                }
578
                $converted[] = $element;
579
            }
580
            // sort the new array (ascending)
581
            usort($converted, ['ScoreDisplay', 'sort_display']);
582
583
            // adjust each score in such a way that
584
            // each score is scaled between 0 and 1
585
            // the highest score in this array will be equal to 1
586
            $converted2 = [];
587
            foreach ($converted as $element) {
588
                $newelement = [];
589
                if (isset($highest) && !empty($highest) && $highest > 0) {
590
                    $newelement['score'] = $element['score'] / $highest;
591
                } else {
592
                    $newelement['score'] = 0;
593
                }
594
                $newelement['display'] = $element['display'];
595
                $converted2[] = $newelement;
596
            }
597
598
            return $converted2;
599
        } else {
600
            return null;
601
        }
602
    }
603
604
    /**
605
     * @param array $item1
606
     * @param array $item2
607
     *
608
     * @return int
609
     */
610
    private function sort_display($item1, $item2)
611
    {
612
        if ($item1['score'] === $item2['score']) {
613
            return 0;
614
        } else {
615
            return $item1['score'] < $item2['score'] ? -1 : 1;
616
        }
617
    }
618
}
619