Passed
Push — master ( 16cab1...51d316 )
by
unknown
18:45 queued 09:14
created

LearnpathLink::calc_score()   B

Complexity

Conditions 11
Paths 44

Size

Total Lines 60
Code Lines 43

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 11
eloc 43
nc 44
nop 2
dl 0
loc 60
rs 7.3166
c 1
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\CoreBundle\Framework\Container;
6
use Chamilo\CourseBundle\Entity\CLp;
7
8
/**
9
 * Defines a gradebook LearnpathLink object.
10
 *
11
 * @author Yannick Warnier <[email protected]>
12
 * @author Bert Steppé
13
 */
14
class LearnpathLink extends AbstractLink
15
{
16
    private $learnpath_table;
17
    private $learnpath_data;
18
19
    /**
20
     * Constructor.
21
     */
22
    public function __construct()
23
    {
24
        parent::__construct();
25
        $this->set_type(LINK_LEARNPATH);
26
    }
27
28
    /**
29
     * Generate an array of all learnpaths available.
30
     *
31
     * @return array 2-dimensional array - every element contains 2 subelements (id, name)
32
     */
33
    public function get_all_links()
34
    {
35
        if (empty($this->getCourseId())) {
36
            return [];
37
        }
38
39
        $lpRepo = Container::getLpRepository();
40
        $session = api_get_session_entity();
41
        $course = api_get_course_entity();
42
43
        $qb = $lpRepo->getResourcesByCourse($course, $session);
44
        $lps = $qb->getQuery()->getResult();
45
46
        $list = [];
47
        /** @var CLp $lp */
48
        foreach ($lps as $lp) {
49
            $list[] = [$lp->getIid(), $lp->getTitle()];
50
        }
51
52
        return $list;
53
    }
54
55
    /**
56
     * Has anyone used this learnpath yet ?
57
     */
58
    public function has_results()
59
    {
60
        $tbl_stats = Database::get_course_table(TABLE_LP_VIEW);
61
        $sql = "SELECT count(id) AS number FROM $tbl_stats
62
				WHERE lp_id = ".$this->get_ref_id();
63
        $result = Database::query($sql);
64
        $number = Database::fetch_array($result, 'NUM');
65
66
        return 0 != $number[0];
67
    }
68
69
    /**
70
     * Get the progress of this learnpath. Only the last attempt are taken into account.
71
     *
72
     * @param $studentId student id (default: all students who have results - then the average is returned)
73
     * @param $type The type of score we want to get: best|average|ranking
74
     *
75
     * @return array (score, max) if student is given
76
     *               array (sum of scores, number of scores) otherwise
77
     *               or null if no scores available
78
     */
79
    public function calc_score($studentId = null, $type = null)
80
    {
81
        $tbl_stats = Database::get_course_table(TABLE_LP_VIEW);
82
        $session_id = $this->get_session_id();
83
84
        $sql = "SELECT * FROM $tbl_stats
85
                WHERE lp_id = ".$this->get_ref_id();
86
87
        if (isset($studentId)) {
88
            $sql .= ' AND user_id = '.intval($studentId);
89
        }
90
91
        // order by id, that way the student's first attempt is accessed first
92
        $sql .= ' ORDER BY view_count DESC';
93
94
        $scores = Database::query($sql);
95
        // for 1 student
96
        if (isset($studentId)) {
97
            if ($data = Database::fetch_assoc($scores)) {
98
                return [$data['progress'], 100];
99
            } else {
100
                return null;
101
            }
102
        } else {
103
            // all students -> get average
104
            $students = []; // user list, needed to make sure we only
105
            // take first attempts into account
106
            $rescount = 0;
107
            $sum = 0;
108
            $bestResult = 0;
109
            $sumResult = 0;
110
            while ($data = Database::fetch_array($scores)) {
111
                if (!(array_key_exists($data['user_id'], $students))) {
112
                    $students[$data['user_id']] = $data['progress'];
113
                    $rescount++;
114
                    $sum += $data['progress'] / 100;
115
                    $sumResult += $data['progress'];
116
117
                    if ($data['progress'] > $bestResult) {
118
                        $bestResult = $data['progress'];
119
                    }
120
                }
121
            }
122
123
            if (0 == $rescount) {
124
                return [null, null];
125
            } else {
126
                switch ($type) {
127
                    case 'best':
128
                        return [$bestResult, 100];
129
                        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...
130
                    case 'average':
131
                        return [$sumResult / $rescount, 100];
132
                        break;
133
                    case 'ranking':
134
                        return AbstractLink::getCurrentUserRanking($studentId, $students);
135
                        break;
136
                    default:
137
                        return [$sum, $rescount];
138
                        break;
139
                }
140
            }
141
        }
142
    }
143
144
    /**
145
     * Get URL where to go to if the user clicks on the link.
146
     */
147
    public function get_link()
148
    {
149
        $session_id = $this->get_session_id();
150
        $url = api_get_path(WEB_CODE_PATH).'lp/lp_controller.php?'.api_get_cidreq_params(
151
            $this->getCourseId(),
152
                $session_id
153
        ).'&gradebook=view';
154
155
        if (!api_is_allowed_to_edit() || null == $this->calc_score(api_get_user_id())) {
156
            $url .= '&action=view&lp_id='.$this->get_ref_id();
157
        } else {
158
            $url .= '&action=build&lp_id='.$this->get_ref_id();
159
        }
160
161
        return $url;
162
    }
163
164
    /**
165
     * Get name to display: same as learnpath title.
166
     */
167
    public function get_name()
168
    {
169
        $data = $this->get_learnpath_data();
170
171
        return $data['title'];
172
    }
173
174
    /**
175
     * Get description to display: same as learnpath description.
176
     */
177
    public function get_description()
178
    {
179
        $data = $this->get_learnpath_data();
180
181
        return $data['description'];
182
    }
183
184
    /**
185
     * Check if this still links to a learnpath.
186
     */
187
    public function is_valid_link()
188
    {
189
        $sql = 'SELECT count(iid) FROM '.$this->get_learnpath_table().'
190
                WHERE iid = '.$this->get_ref_id().' ';
191
        $result = Database::query($sql);
192
        $number = Database::fetch_row($result, 'NUM');
193
194
        return 0 != $number[0];
195
    }
196
197
    public function get_type_name()
198
    {
199
        return get_lang('Learning paths');
200
    }
201
202
    public function needs_name_and_description()
203
    {
204
        return false;
205
    }
206
207
    public function needs_max()
208
    {
209
        return false;
210
    }
211
212
    public function needs_results()
213
    {
214
        return false;
215
    }
216
217
    public function is_allowed_to_change_name()
218
    {
219
        return false;
220
    }
221
222
    public function get_icon_name()
223
    {
224
        return 'learnpath';
225
    }
226
227
    /**
228
     * Lazy load function to get the database table of the learnpath.
229
     */
230
    private function get_learnpath_table()
231
    {
232
        $this->learnpath_table = Database::get_course_table(TABLE_LP_MAIN);
233
234
        return $this->learnpath_table;
235
    }
236
237
    /**
238
     * Lazy load function to get the database contents of this learnpath.
239
     */
240
    private function get_learnpath_data()
241
    {
242
        if (!isset($this->learnpath_data)) {
243
            $sql = 'SELECT * FROM '.$this->get_learnpath_table().'
244
                    WHERE iid = '.$this->get_ref_id().' ';
245
            $result = Database::query($sql);
246
            $this->learnpath_data = Database::fetch_array($result);
247
        }
248
249
        return $this->learnpath_data;
250
    }
251
}
252