Passed
Pull Request — 1.11.x (#4900)
by Angel Fernando Quiroz
10:54
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
$monitoringLogRepository = $em->getRepository(MonitoringLog::class);
31
32
if (!$plugin->isEnabled(true)) {
33
    api_not_allowed(true);
34
}
35
36
$params = $request->query->all();
37
38
$results = findResults($params, $em, $plugin);
39
40
$data = [];
41
42
/** @var array<string, mixed> $result */
43
foreach ($results as $result) {
44
    /** @var TrackEExercises $trackExe */
45
    $trackExe = $result['exe'];
46
    $user = api_get_user_entity($trackExe->getExeUserId());
47
48
    $outfocusedLimitCount = $focusedLogRepository->countByActionInExe($trackExe, FocusedLog::TYPE_OUTFOCUSED_LIMIT);
49
    $timeLimitCount = $focusedLogRepository->countByActionInExe($trackExe, FocusedLog::TYPE_TIME_LIMIT);
50
51
    $exercise = new Exercise($trackExe->getCId());
52
    $exercise->read($trackExe->getExeExoId());
53
54
    $quizType = (int) $exercise->selectType();
55
56
    if ($trackExe->getSessionId()) {
57
        $data[] = [
58
            get_lang('SessionName'),
59
            api_get_session_entity($trackExe->getSessionId())->getName(),
60
        ];
61
    }
62
    $data[] = [
63
        get_lang('Course'),
64
        api_get_course_entity($trackExe->getCId())->getTitle(),
65
    ];
66
    $data[] = [
67
        get_lang('ExerciseName'),
68
        $exercise->getUnformattedTitle(),
69
    ];
70
    $data[] = [
71
        get_lang('Learner'),
72
        $user->getUsername(),
73
        $user->getFirstname(),
74
        $user->getLastname(),
75
    ];
76
    $data[] = [
77
        get_lang('StartDate'),
78
        api_get_local_time($result['exe']->getStartDate(), null, null, true, true, true),
79
        get_lang('EndDate'),
80
        api_get_local_time($result['exe']->getExeDate(), null, null, true, true, true),
81
    ];
82
    $data[] = [
83
        $plugin->get_lang('Motive'),
84
        $plugin->calculateMotive($outfocusedLimitCount, $timeLimitCount),
85
    ];
86
    $data[] = [];
87
88
    if (ONE_PER_PAGE === $quizType) {
89
        $questionList = explode(',', $trackExe->getDataTracking());
90
91
        $row = [
92
            get_lang('Level'),
93
            get_lang('DateExo'),
94
            get_lang('Score'),
95
            $plugin->get_lang('Outfocused'),
96
            $plugin->get_lang('Returns'),
97
        ];
98
99
        if ($monitoringPluginIsEnabled) {
100
            $row[] = $monitoringPlugin->get_lang('Snapshots');
101
        }
102
103
        $data[] = $row;
104
105
        foreach ($questionList as $idx => $questionId) {
106
            $attempt = $attempsRepository->findOneBy(
107
                ['exeId' => $trackExe->getExeId(), 'questionId' => $questionId],
108
                ['tms' => 'DESC']
109
            );
110
111
            if (!$attempt) {
112
                continue;
113
            }
114
115
            $result = $exercise->manage_answer(
116
                $trackExe->getExeId(),
117
                $questionId,
118
                null,
119
                'exercise_result',
120
                false,
121
                false,
122
                true,
123
                false,
124
                $exercise->selectPropagateNeg()
125
            );
126
127
            $row = [
128
                get_lang('QuestionNumber').' '.($idx + 1),
129
                api_get_local_time($attempt->getTms()),
130
                $result['score'].' / '.$result['weight'],
131
                $focusedLogRepository->countByActionAndLevel($trackExe, FocusedLog::TYPE_OUTFOCUSED, $questionId),
132
                $focusedLogRepository->countByActionAndLevel($trackExe, FocusedLog::TYPE_RETURN, $questionId),
133
            ];
134
135
            if ($monitoringPluginIsEnabled) {
136
                $monitoringLogsByQuestion = $monitoringLogRepository->findByLevelAndExe($questionId, $trackExe);
137
                $snapshotList = [];
138
139
                /** @var MonitoringLog $logByQuestion */
140
                foreach ($monitoringLogsByQuestion as $logByQuestion) {
141
                    $snapshotUrl = ExerciseMonitoringPlugin::generateSnapshotUrl(
142
                        $user->getId(),
143
                        $logByQuestion->getImageFilename()
144
                    );
145
                    $snapshotList[] = api_get_local_time($logByQuestion->getCreatedAt()).' '.$snapshotUrl;
146
                }
147
148
                $row[] = implode(PHP_EOL, $snapshotList);
149
            }
150
151
            $data[] = $row;
152
        }
153
    } elseif (ALL_ON_ONE_PAGE === $quizType) {
154
    }
155
156
    $data[] = [];
157
    $data[] = [];
158
}
159
160
//var_dump($data);
161
Export::arrayToXls($data);
162
163
function getSessionIdFromFormValues(array $formValues, array $fieldVariableList): array
164
{
165
    $fieldItemIdList = [];
166
    $objFieldValue = new ExtraFieldValue('session');
167
168
    foreach ($fieldVariableList as $fieldVariable) {
169
        if (!isset($formValues["extra_$fieldVariable"])) {
170
            continue;
171
        }
172
173
        $itemValue = $objFieldValue->get_item_id_from_field_variable_and_field_value(
174
            $fieldVariable,
175
            $formValues["extra_$fieldVariable"]
176
        );
177
178
        if ($itemValue) {
179
            $fieldItemIdList[] = (int) $itemValue['item_id'];
180
        }
181
    }
182
183
    return array_unique($fieldItemIdList);
184
}
185
186
function findResults(array $formValues, EntityManagerInterface $em, ExerciseFocusedPlugin $plugin)
187
{
188
    $cId = api_get_course_int_id();
189
190
    $qb = $em->createQueryBuilder();
191
    $qb
192
        ->select('te AS exe, q.title, te.startDate , u.firstname, u.lastname, u.username')
193
        ->from(TrackEExercises::class, 'te')
194
        ->innerJoin(CQuiz::class, 'q', Join::WITH, 'te.exeExoId = q.iid')
195
        ->innerJoin(User::class, 'u', Join::WITH, 'te.exeUserId = u.id');
196
197
    $params = [];
198
199
    if ($cId) {
200
        $qb->andWhere($qb->expr()->eq('te.cId', ':cId'));
201
202
        $params['cId'] = $cId;
203
    }
204
205
    $sessionItemIdList = getSessionIdFromFormValues(
206
        $formValues,
207
        $plugin->getSessionFieldList()
208
    );
209
210
    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...
211
        $qb->andWhere($qb->expr()->in('te.sessionId', ':sessionItemIdList'));
212
213
        $params['sessionItemIdList'] = $sessionItemIdList;
214
    } else {
215
        $qb->andWhere($qb->expr()->isNull('te.sessionId'));
216
    }
217
218
    if (!empty($formValues['username'])) {
219
        $qb->andWhere($qb->expr()->eq('u.username', ':username'));
220
221
        $params['username'] = $formValues['username'];
222
    }
223
224
    if (!empty($formValues['firstname'])) {
225
        $qb->andWhere($qb->expr()->eq('u.firstname', ':firstname'));
226
227
        $params['firstname'] = $formValues['firstname'];
228
    }
229
230
    if (!empty($formValues['lastname'])) {
231
        $qb->andWhere($qb->expr()->eq('u.lastname', ':lastname'));
232
233
        $params['lastname'] = $formValues['lastname'];
234
    }
235
236
    if (!empty($formValues['start_date'])) {
237
        $qb->andWhere(
238
            $qb->expr()->andX(
239
                $qb->expr()->gte('te.startDate', ':start_date'),
240
                $qb->expr()->lte('te.exeDate', ':end_date')
241
            )
242
        );
243
244
        $params['start_date'] = api_get_utc_datetime($formValues['start_date'].' 00:00:00', false, true);
245
        $params['end_date'] = api_get_utc_datetime($formValues['start_date'].' 23:59:59', false, true);
246
    }
247
248
    if (empty($params)) {
249
        return [];
250
    }
251
252
    if ($cId && !empty($formValues['id'])) {
253
        $qb->andWhere($qb->expr()->eq('q.iid', ':q_id'));
254
255
        $params['q_id'] = $formValues['id'];
256
    }
257
258
    $qb->setParameters($params);
259
260
    $query = $qb->getQuery();
261
262
    return $query->getResult();
263
}
264