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