Passed
Pull Request — 1.11.x (#4900)
by Angel Fernando Quiroz
10:14
created

findResults()   C

Complexity

Conditions 10
Paths 192

Size

Total Lines 77
Code Lines 43

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 43
c 1
b 0
f 0
dl 0
loc 77
rs 6.9
cc 10
nc 192
nop 3

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\Entity\TrackEAttempt;
6
use Chamilo\CoreBundle\Entity\TrackEExercises;
7
use Chamilo\CourseBundle\Entity\CQuiz;
8
use Chamilo\PluginBundle\ExerciseFocused\Entity\Log as FocusedLog;
9
use Chamilo\PluginBundle\ExerciseMonitoring\Entity\Log as MonitoringLog;
10
use Chamilo\UserBundle\Entity\User;
11
use Doctrine\ORM\EntityManagerInterface;
12
use Doctrine\ORM\Query\Expr\Join;
13
use Symfony\Component\HttpFoundation\Request as HttpRequest;
0 ignored issues
show
Bug introduced by
This use statement conflicts with another class in this namespace, HttpRequest. Consider defining an alias.

Let?s assume that you have a directory layout like this:

.
|-- OtherDir
|   |-- Bar.php
|   `-- Foo.php
`-- SomeDir
    `-- Foo.php

and let?s assume the following content of Bar.php:

// Bar.php
namespace OtherDir;

use SomeDir\Foo; // This now conflicts the class OtherDir\Foo

If both files OtherDir/Foo.php and SomeDir/Foo.php are loaded in the same runtime, you will see a PHP error such as the following:

PHP Fatal error:  Cannot use SomeDir\Foo as Foo because the name is already in use in OtherDir/Foo.php

However, as OtherDir/Foo.php does not necessarily have to be loaded and the error is only triggered if it is loaded before OtherDir/Bar.php, this problem might go unnoticed for a while. In order to prevent this error from surfacing, you must import the namespace with a different alias:

// Bar.php
namespace OtherDir;

use SomeDir\Foo as SomeDirFoo; // There is no conflict anymore.
Loading history...
14
15
require_once __DIR__.'/../../../main/inc/global.inc.php';
16
17
api_protect_course_script(true);
18
19
if (!api_is_allowed_to_edit()) {
20
    api_not_allowed(true);
21
}
22
23
$plugin = ExerciseFocusedPlugin::create();
24
$monitoringPlugin = ExerciseMonitoringPlugin::create();
25
$monitoringPluginIsEnabled = $monitoringPlugin->isEnabled(true);
26
$request = HttpRequest::createFromGlobals();
27
$em = Database::getManager();
28
$focusedLogRepository = $em->getRepository(FocusedLog::class);
29
$attempsRepository = $em->getRepository(TrackEAttempt::class);
30
31
if (!$plugin->isEnabled(true)) {
32
    api_not_allowed(true);
33
}
34
35
$params = $request->query->all();
36
37
$results = findResults($params, $em, $plugin);
38
39
$data = [];
40
41
/** @var array<string, mixed> $result */
42
foreach ($results as $result) {
43
    /** @var TrackEExercises $trackExe */
44
    $trackExe = $result['exe'];
45
    $user = api_get_user_entity($trackExe->getExeUserId());
46
47
    $outfocusedLimitCount = $focusedLogRepository->countByActionInExe($trackExe, FocusedLog::TYPE_OUTFOCUSED_LIMIT);
48
    $timeLimitCount = $focusedLogRepository->countByActionInExe($trackExe, FocusedLog::TYPE_TIME_LIMIT);
49
50
    $exercise = new Exercise($trackExe->getCId());
51
    $exercise->read($trackExe->getExeExoId());
52
53
    $quizType = (int) $exercise->selectType();
54
55
    if ($trackExe->getSessionId()) {
56
        $data[] = [
57
            get_lang('SessionName'),
58
            api_get_session_entity($trackExe->getSessionId())->getName(),
59
        ];
60
    }
61
    $data[] = [
62
        get_lang('Course'),
63
        api_get_course_entity($trackExe->getCId())->getTitle(),
64
    ];
65
    $data[] = [
66
        get_lang('ExerciseName'),
67
        $exercise->getUnformattedTitle(),
68
    ];
69
    $data[] = [
70
        get_lang('Student'),
71
        $user->getUsername(),
72
        $user->getFirstname(),
73
        $user->getLastname(),
74
    ];
75
    $data[] = [
76
        get_lang('StartDate'),
77
        api_get_local_time($result['exe']->getStartDate(), null, null, true, true, true),
78
        get_lang('EndDate'),
79
        api_get_local_time($result['exe']->getExeDate(), null, null, true, true, true),
80
    ];
81
    $data[] = [
82
        $plugin->get_lang('Motive'),
83
        $plugin->calculateMotive($outfocusedLimitCount, $timeLimitCount),
84
    ];
85
    $data[] = [];
86
87
    $row = [
88
        $plugin->get_lang('LevelReached'),
89
        get_lang('DateExo'),
90
        get_lang('Score'),
91
        $plugin->get_lang('Outfocused'),
92
        $plugin->get_lang('Returns'),
93
    ];
94
95
    if (ONE_PER_PAGE === $quizType) {
96
        $questionList = explode(',', $trackExe->getDataTracking());
97
98
        if ($monitoringPluginIsEnabled) {
99
            $row[] = $monitoringPlugin->get_lang('Snapshots');
100
        }
101
102
        $data[] = $row;
103
104
        foreach ($questionList as $idx => $questionId) {
105
            $attempt = $attempsRepository->findOneBy(
106
                ['exeId' => $trackExe->getExeId(), 'questionId' => $questionId],
107
                ['tms' => 'DESC']
108
            );
109
110
            if (!$attempt) {
111
                continue;
112
            }
113
114
            $result = $exercise->manage_answer(
115
                $trackExe->getExeId(),
116
                $questionId,
117
                null,
118
                'exercise_result',
119
                false,
120
                false,
121
                true,
122
                false,
123
                $exercise->selectPropagateNeg()
124
            );
125
126
            $row = [
127
                get_lang('QuestionNumber').' '.($idx + 1),
128
                api_get_local_time($attempt->getTms()),
129
                $result['score'].' / '.$result['weight'],
130
                $focusedLogRepository->countByActionAndLevel($trackExe, FocusedLog::TYPE_OUTFOCUSED, $questionId),
131
                $focusedLogRepository->countByActionAndLevel($trackExe, FocusedLog::TYPE_RETURN, $questionId),
132
                getSnapshotListForLevel($questionId, $trackExe),
133
            ];
134
135
            $data[] = $row;
136
        }
137
    } elseif (ALL_ON_ONE_PAGE === $quizType) {
138
    }
139
140
    $data[] = [];
141
    $data[] = [];
142
}
143
144
//var_dump($data);
145
Export::arrayToXls($data);
146
147
function getSessionIdFromFormValues(array $formValues, array $fieldVariableList): array
148
{
149
    $fieldItemIdList = [];
150
    $objFieldValue = new ExtraFieldValue('session');
151
152
    foreach ($fieldVariableList as $fieldVariable) {
153
        if (!isset($formValues["extra_$fieldVariable"])) {
154
            continue;
155
        }
156
157
        $itemValue = $objFieldValue->get_item_id_from_field_variable_and_field_value(
158
            $fieldVariable,
159
            $formValues["extra_$fieldVariable"]
160
        );
161
162
        if ($itemValue) {
163
            $fieldItemIdList[] = (int) $itemValue['item_id'];
164
        }
165
    }
166
167
    return array_unique($fieldItemIdList);
168
}
169
170
function findResults(array $formValues, EntityManagerInterface $em, ExerciseFocusedPlugin $plugin)
171
{
172
    $cId = api_get_course_int_id();
173
174
    $qb = $em->createQueryBuilder();
175
    $qb
176
        ->select('te AS exe, q.title, te.startDate , u.firstname, u.lastname, u.username')
177
        ->from(TrackEExercises::class, 'te')
178
        ->innerJoin(CQuiz::class, 'q', Join::WITH, 'te.exeExoId = q.iid')
179
        ->innerJoin(User::class, 'u', Join::WITH, 'te.exeUserId = u.id');
180
181
    $params = [];
182
183
    if ($cId) {
184
        $qb->andWhere($qb->expr()->eq('te.cId', ':cId'));
185
186
        $params['cId'] = $cId;
187
    }
188
189
    $sessionItemIdList = getSessionIdFromFormValues(
190
        $formValues,
191
        $plugin->getSessionFieldList()
192
    );
193
194
    if ($sessionItemIdList) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $sessionItemIdList of type array is implicitly converted to a boolean; are you sure this is intended? If so, consider using ! empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
195
        $qb->andWhere($qb->expr()->in('te.sessionId', ':sessionItemIdList'));
196
197
        $params['sessionItemIdList'] = $sessionItemIdList;
198
    } else {
199
        $qb->andWhere($qb->expr()->isNull('te.sessionId'));
200
    }
201
202
    if (!empty($formValues['username'])) {
203
        $qb->andWhere($qb->expr()->eq('u.username', ':username'));
204
205
        $params['username'] = $formValues['username'];
206
    }
207
208
    if (!empty($formValues['firstname'])) {
209
        $qb->andWhere($qb->expr()->eq('u.firstname', ':firstname'));
210
211
        $params['firstname'] = $formValues['firstname'];
212
    }
213
214
    if (!empty($formValues['lastname'])) {
215
        $qb->andWhere($qb->expr()->eq('u.lastname', ':lastname'));
216
217
        $params['lastname'] = $formValues['lastname'];
218
    }
219
220
    if (!empty($formValues['start_date'])) {
221
        $qb->andWhere(
222
            $qb->expr()->andX(
223
                $qb->expr()->gte('te.startDate', ':start_date'),
224
                $qb->expr()->lte('te.exeDate', ':end_date')
225
            )
226
        );
227
228
        $params['start_date'] = api_get_utc_datetime($formValues['start_date'].' 00:00:00', false, true);
229
        $params['end_date'] = api_get_utc_datetime($formValues['start_date'].' 23:59:59', false, true);
230
    }
231
232
    if (empty($params)) {
233
        return [];
234
    }
235
236
    if ($cId && !empty($formValues['id'])) {
237
        $qb->andWhere($qb->expr()->eq('q.iid', ':q_id'));
238
239
        $params['q_id'] = $formValues['id'];
240
    }
241
242
    $qb->setParameters($params);
243
244
    $query = $qb->getQuery();
245
246
    return $query->getResult();
247
}
248
249
function getSnapshotListForLevel(int $level, TrackEExercises $trackExe): string
250
{
251
    $monitoringPluginIsEnabled = ExerciseMonitoringPlugin::create()->isEnabled(true);
252
253
    if (!$monitoringPluginIsEnabled) {
254
        return '';
255
    }
256
257
    $user = api_get_user_entity($trackExe->getExeUserId());
258
    $monitoringLogRepository = Database::getManager()->getRepository(MonitoringLog::class);
259
260
    $monitoringLogsByQuestion = $monitoringLogRepository->findByLevelAndExe($level, $trackExe);
261
    $snapshotList = [];
262
263
    /** @var MonitoringLog $logByQuestion */
264
    foreach ($monitoringLogsByQuestion as $logByQuestion) {
265
        $snapshotUrl = ExerciseMonitoringPlugin::generateSnapshotUrl(
266
            $user->getId(),
267
            $logByQuestion->getImageFilename()
268
        );
269
        $snapshotList[] = api_get_local_time($logByQuestion->getCreatedAt()).' '.$snapshotUrl;
270
    }
271
272
    return implode(PHP_EOL, $snapshotList);
273
}
274