Passed
Push — master ( 49c89f...65060b )
by Julito
10:01
created

Result::exists()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 14
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 9
c 0
b 0
f 0
nc 1
nop 0
dl 0
loc 14
rs 9.9666
1
<?php
2
/* For licensing terms, see /license.txt */
3
4
/**
5
 * Defines a gradebook Result object.
6
 *
7
 * @author Bert Steppé, Stijn Konings
8
 *
9
 * @package chamilo.gradebook
10
 */
11
class Result
12
{
13
    private $id;
14
    private $user_id;
15
    private $evaluation;
16
    private $created_at;
17
    private $score;
18
19
    /**
20
     * Result constructor.
21
     */
22
    public function __construct()
23
    {
24
        $this->created_at = api_get_utc_datetime();
25
    }
26
27
    public function get_id()
28
    {
29
        return $this->id;
30
    }
31
32
    public function get_user_id()
33
    {
34
        return $this->user_id;
35
    }
36
37
    public function get_evaluation_id()
38
    {
39
        return $this->evaluation;
40
    }
41
42
    public function get_date()
43
    {
44
        return $this->created_at;
45
    }
46
47
    public function get_score()
48
    {
49
        return $this->score;
50
    }
51
52
    public function set_id($id)
53
    {
54
        $this->id = $id;
55
    }
56
57
    public function set_user_id($user_id)
58
    {
59
        $this->user_id = $user_id;
60
    }
61
62
    public function set_evaluation_id($evaluation_id)
63
    {
64
        $this->evaluation = $evaluation_id;
65
    }
66
67
    /**
68
     * @param string $creation_date
69
     */
70
    public function set_date($creation_date)
71
    {
72
        $this->created_at = $creation_date;
73
    }
74
75
    /**
76
     * @param float $score
77
     */
78
    public function set_score($score)
79
    {
80
        $this->score = $score;
81
    }
82
83
    /**
84
     * Retrieve results and return them as an array of Result objects.
85
     *
86
     * @param $id result id
87
     * @param $user_id user id (student)
88
     * @param $evaluation_id evaluation where this is a result for
89
     *
90
     * @return array
91
     */
92
    public static function load($id = null, $user_id = null, $evaluation_id = null)
93
    {
94
        $tbl_user = Database::get_main_table(TABLE_MAIN_USER);
95
        $tbl_grade_results = Database::get_main_table(TABLE_MAIN_GRADEBOOK_RESULT);
96
        $tbl_course_rel_course = Database::get_main_table(TABLE_MAIN_COURSE_USER);
97
        $tbl_session_rel_course_user = Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
98
        $sessionId = api_get_session_id();
99
        $list_user_course_list = [];
100
101
        if (is_null($id) && is_null($user_id) && !is_null($evaluation_id)) {
102
            // Verified_if_exist_evaluation
103
            $sql = 'SELECT COUNT(*) AS count
104
                    FROM '.$tbl_grade_results.'
105
                    WHERE evaluation_id="'.Database::escape_string($evaluation_id).'"';
106
107
            $result = Database::query($sql);
108
            $existEvaluation = Database::result($result, 0, 0);
109
110
            if ($existEvaluation != 0) {
111
                if ($sessionId) {
112
                    $sql = 'SELECT c_id, user_id as user_id, status
113
                            FROM '.$tbl_session_rel_course_user.'
114
							WHERE
115
							    status= 0 AND
116
							    c_id = "'.api_get_course_int_id().'" AND
117
							    session_id = '.$sessionId;
118
                } else {
119
                    $sql = 'SELECT c_id, user_id, status
120
                            FROM '.$tbl_course_rel_course.'
121
                            WHERE status ="'.STUDENT.'" AND c_id = "'.api_get_course_int_id().'" ';
122
                }
123
124
                $res_course_rel_user = Database::query($sql);
125
                while ($row_course_rel_user = Database::fetch_array($res_course_rel_user, 'ASSOC')) {
126
                    $list_user_course_list[] = $row_course_rel_user;
127
                }
128
                $current_date = api_get_utc_datetime();
129
                for ($i = 0; $i < count($list_user_course_list); $i++) {
0 ignored issues
show
Performance Best Practice introduced by
It seems like you are calling the size function count() as part of the test condition. You might want to compute the size beforehand, and not on each iteration.

If the size of the collection does not change during the iteration, it is generally a good practice to compute it beforehand, and not on each iteration:

for ($i=0; $i<count($array); $i++) { // calls count() on each iteration
}

// Better
for ($i=0, $c=count($array); $i<$c; $i++) { // calls count() just once
}
Loading history...
130
                    $sql_verified = 'SELECT COUNT(*) AS count
131
                                    FROM '.$tbl_grade_results.'
132
                                    WHERE
133
                                        user_id="'.intval($list_user_course_list[$i]['user_id']).'" AND
134
                                        evaluation_id="'.intval($evaluation_id).'";';
135
                    $res_verified = Database::query($sql_verified);
136
                    $info_verified = Database::result($res_verified, 0, 0);
137
                    if ($info_verified == 0) {
138
                        $sql_insert = 'INSERT INTO '.$tbl_grade_results.'(user_id,evaluation_id,created_at,score)
139
									   VALUES ("'.intval($list_user_course_list[$i]['user_id']).'","'.intval($evaluation_id).'","'.$current_date.'",0);';
140
                        Database::query($sql_insert);
141
                    }
142
                }
143
            }
144
        }
145
146
        $userIdList = [];
147
        foreach ($list_user_course_list as $data) {
148
            $userIdList[] = $data['user_id'];
149
        }
150
        $userIdListToString = implode("', '", $userIdList);
151
152
        $sql = "SELECT lastname, gr.id, gr.user_id, gr.evaluation_id, gr.created_at, gr.score
153
                FROM $tbl_grade_results gr
154
                INNER JOIN $tbl_user u
155
                ON gr.user_id = u.user_id ";
156
157
        if (!empty($userIdList)) {
158
            $sql .= " AND u.user_id IN ('$userIdListToString')";
159
        }
160
161
        $paramcount = 0;
162
        if (!empty($id)) {
163
            $sql .= ' WHERE gr.id = '.intval($id);
164
            $paramcount++;
165
        }
166
        if (!empty($user_id)) {
167
            if ($paramcount != 0) {
168
                $sql .= ' AND';
169
            } else {
170
                $sql .= ' WHERE';
171
            }
172
            $sql .= ' gr.user_id = '.intval($user_id);
173
            $paramcount++;
174
        }
175
        if (!empty($evaluation_id)) {
176
            if ($paramcount != 0) {
177
                $sql .= ' AND';
178
            } else {
179
                $sql .= ' WHERE';
180
            }
181
            $sql .= ' gr.evaluation_id = '.intval($evaluation_id);
182
            $paramcount++;
183
        }
184
        $sql .= ' ORDER BY u.lastname, u.firstname';
185
186
        $result = Database::query($sql);
187
        $allres = [];
188
        while ($data = Database::fetch_array($result)) {
189
            $res = new Result();
190
            $res->set_id($data['id']);
191
            $res->set_user_id($data['user_id']);
192
            $res->set_evaluation_id($data['evaluation_id']);
193
            $res->set_date(api_get_local_time($data['created_at']));
194
            $res->set_score($data['score']);
195
            $allres[] = $res;
196
        }
197
198
        return $allres;
199
    }
200
201
    /**
202
     * Insert this result into the database.
203
     */
204
    public function add()
205
    {
206
        if (isset($this->user_id) && isset($this->evaluation)) {
207
            $tbl_grade_results = Database::get_main_table(TABLE_MAIN_GRADEBOOK_RESULT);
208
            $sql = "INSERT INTO ".$tbl_grade_results
209
                ." (user_id, evaluation_id,
210
					created_at";
211
            if (isset($this->score)) {
212
                $sql .= ",score";
213
            }
214
            $sql .= ") VALUES
215
					(".(int) $this->get_user_id().", ".(int) $this->get_evaluation_id()
216
                .", '".$this->get_date()."' ";
217
            if (isset($this->score)) {
218
                $sql .= ", ".$this->get_score();
219
            }
220
            $sql .= ")";
221
            Database::query($sql);
222
        } else {
223
            die('Error in Result add: required field empty');
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...
224
        }
225
    }
226
227
    /**
228
     * insert log result.
229
     */
230
    public function addResultLog($userid, $evaluationid)
231
    {
232
        if (isset($userid) && isset($evaluationid)) {
233
            $table = Database::get_main_table(TABLE_MAIN_GRADEBOOK_RESULT_LOG);
234
            $result = new Result();
235
236
            $arr_result = $result->load(null, $userid, $evaluationid);
237
            $arr = get_object_vars($arr_result[0]);
238
239
            $sql = 'INSERT INTO '.$table.' (result_id,user_id, evaluation_id,created_at';
240
            if (isset($arr['score'])) {
241
                $sql .= ',score';
242
            }
243
            $sql .= ') VALUES
244
					('.(int) $arr['id'].','.(int) $arr['user_id'].', '.(int) $arr['evaluation']
245
                .", '".api_get_utc_datetime()."'";
246
            if (isset($arr['score'])) {
247
                $sql .= ', '.$arr['score'];
248
            }
249
            $sql .= ')';
250
251
            Database::query($sql);
252
        } else {
253
            die('Error in Result add: required field empty');
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...
254
        }
255
    }
256
257
    /**
258
     * Update the properties of this result in the database.
259
     */
260
    public function save()
261
    {
262
        $table = Database::get_main_table(TABLE_MAIN_GRADEBOOK_RESULT);
263
        $sql = 'UPDATE '.$table.'
264
                SET user_id = '.$this->get_user_id()
265
            .', evaluation_id = '.$this->get_evaluation_id()
266
            .', score = ';
267
        if (isset($this->score)) {
268
            $sql .= $this->get_score();
269
        } else {
270
            $sql .= 'null';
271
        }
272
        $sql .= ' WHERE id = '.$this->id;
273
        // no need to update creation date
274
        Database::query($sql);
275
    }
276
277
    /**
278
     * Delete this result from the database.
279
     */
280
    public function delete()
281
    {
282
        $table = Database::get_main_table(TABLE_MAIN_GRADEBOOK_RESULT);
283
        $sql = 'DELETE FROM '.$table.' WHERE id = '.$this->id;
284
        Database::query($sql);
285
        $allowMultipleAttempts = api_get_configuration_value('gradebook_multiple_evaluation_attempts');
286
        if ($allowMultipleAttempts) {
287
            $table = Database::get_main_table(TABLE_MAIN_GRADEBOOK_RESULT_ATTEMPT);
288
            $sql = "DELETE FROM $table WHERE result_id = ".$this->id;
289
            Database::query($sql);
290
        }
291
    }
292
293
    /**
294
     * Check if exists a result with its user and evaluation.
295
     *
296
     * @throws \Doctrine\ORM\Query\QueryException
297
     *
298
     * @return bool
299
     */
300
    public function exists()
301
    {
302
        $em = Database::getManager();
303
304
        $result = $em
305
            ->createQuery(
306
                'SELECT COUNT(gr) FROM ChamiloCoreBundle:GradebookResult gr
307
                WHERE gr.evaluationId = :eval_id AND gr.userId = :user_id'
308
            )
309
            ->setParameters(['eval_id' => $this->evaluation, 'user_id' => $this->user_id])
310
            ->getSingleScalarResult();
311
        $count = (int) $result;
312
313
        return $count > 0;
314
    }
315
}
316