Completed
Push — develop ( 505b4c...31ac0b )
by Seth
03:45
created

data-collection.php ➔ collectStatistics()   F

Complexity

Conditions 23
Paths 4325

Size

Total Lines 188
Code Lines 109

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 23
eloc 109
nc 4325
nop 4
dl 0
loc 188
rs 2
c 0
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
0 ignored issues
show
Coding Style Compatibility introduced by
For compatibility and reusability of your code, PSR1 recommends that a file should introduce either new symbols (like classes, functions, etc.) or have side-effects (like outputting something, or including other files), but not both at the same time. The first symbol is defined on line 3 and the first side effect is on line 6.

The PSR-1: Basic Coding Standard recommends that a file should either introduce new symbols, that is classes, functions, constants or similar, or have side effects. Side effects are anything that executes logic, like for example printing output, changing ini settings or writing to a file.

The idea behind this recommendation is that merely auto-loading a class should not change the state of an application. It also promotes a cleaner style of programming and makes your code less prone to errors, because the logic is not spread out all over the place.

To learn more about the PSR-1, please see the PHP-FIG site on the PSR-1.

Loading history...
2
3
define('DEBUGGING', DEBUGGING_LOG);
4
define('IGNORE_LTI', true);
5
6
require_once __DIR__ . '/../common.inc.php';
7
require_once __DIR__ . '/../constants.inc.php';
8
9
// http://stackoverflow.com/a/21896310
10
function hoursRange($lower = 0, $upper = 86400, $step = 3600, $keyFormat = '', $value = '', $valueIsFormat = false)
11
{
12
    $times = array();
13
14
    if (empty( $value ) && $valueIsFormat) {
15
        $value = 'g:i a';
16
    }
17
18
    if (empty($keyFormat)) {
19
        $keyFormat = 'g:i a';
20
    }
21
22
    foreach (range( $lower, $upper, $step ) as $increment) {
23
        $increment = gmdate( $keyFormat, $increment );
24
25
        list( $hour, $minutes ) = explode( ':', $increment );
26
27
        $date = new DateTime( $hour . ':' . $minutes );
28
29
        $times[(string) $increment] = ($valueIsFormat ? $date->format( $value ) : $value);
30
    }
31
32
    return $times;
33
}
34
35
function collectStatistics($term, $api, $sql, $metadata)
36
{
37
    // TODO make this configurable
38
    $courses = $api->get(
39
        '/accounts/132/courses',
40
        array(
41
            'with_enrollments' => 'true',
42
            'enrollment_term_id' => $term
43
        )
44
    );
45
46
    // so that everything has a consistent benchmark
47
    $timestamp = time();
48
49
    foreach ($courses as $course) {
50
        $statistic = array(
51
            'timestamp' => date(DATE_ISO8601, $timestamp),
52
            'course[id]' => $course['id'],
53
            'course[name]' => $course['name'],
54
            'course[account_id]' => $course['account_id'],
55
            'gradebook_url' => 'https://' . parse_url($metadata['CANVAS_API_URL'], PHP_URL_HOST) . "/courses/{$course['id']}/gradebook2",
56
            'assignments_due_count' => 0,
57
            'dateless_assignment_count' => 0,
58
            'created_after_due_count' => 0,
59
            'gradeable_assignment_count' => 0,
60
            'graded_assignment_count' => 0,
61
            'zero_point_assignment_count' => 0,
62
            'analytics_page' => $metadata['APP_URL'] . "/course-summary.php?course_id={$course['id']}"
63
        );
64
65
        $teacherIds = array();
66
        $teacherNames = array();
67
        $teachers = $api->get(
68
            "/courses/{$course['id']}/enrollments",
69
            array(
70
                'type[]' => 'TeacherEnrollment'
71
            )
72
        );
73
        foreach ($teachers as $teacher) {
74
            $teacherIds[] = $teacher['user']['id'];
75
            $teacherNames[] = $teacher['user']['sortable_name'];
76
        }
77
        $statistic['teacher[id]s'] = serialize($teacherIds);
78
        $statistic['teacher[sortable_name]s'] = serialize($teacherNames);
79
80
        $account = $api->get("/accounts/{$course['account_id']}");
81
        $statistic['account[name]'] = $account['name'];
82
83
        // ignore classes with no teachers (how do they even exist? weird.)
84
        if (count($teacherIds) != 0) {
85
            $statistic['student_count'] = 0;
86
            $students = $api->get(
87
                "/courses/{$course['id']}/enrollments",
88
                array(
89
                    'type[]' => 'StudentEnrollment'
90
                )
91
            );
92
            $statistic['student_count'] = $students->count();
93
94
            // ignore classes with no students
95
            if ($statistic['student_count'] != 0) {
96
                $assignments = $api->get(
97
                    "/courses/{$course['id']}/assignments"
98
                );
99
100
                $gradedSubmissionsCount = 0;
101
                $turnAroundTimeTally = 0;
102
                $leadTimeTally = 0;
103
                $createdModifiedHistogram = array(
104
                    HISTOGRAM_CREATED => hoursRange(0, 86400, 3600, '', 0),
105
                    HISTOGRAM_MODIFIED => hoursRange(0, 86400, 3600, '', 0)
106
                );
107
108
                foreach ($assignments as $assignment) {
109
                    // ignore unpublished assignments
110
                    if ($assignment['published'] == true) {
111
                        // check for due dates
112
                        $dueDate = new DateTime($assignment['due_at']);
113
                        $dueDate->setTimeZone(new DateTimeZone(SCHOOL_TIME_ZONE));
114
                        if (($timestamp - $dueDate->getTimestamp()) > 0) {
115
                            $statistic['assignments_due_count']++;
116
117
                            // update created_modified_histogram
118
                            $createdAt = new DateTime($assignment['created_at']);
119
                            $createdAt->setTimeZone(new DateTimeZone(SCHOOL_TIME_ZONE));
120
                            $updatedAt = new DateTime($assignment['updated_at']);
121
                            $updatedAt->setTimeZone(new DateTimeZone(SCHOOL_TIME_ZONE));
122
                            $createdModifiedHistogram[HISTOGRAM_CREATED][$createdAt->format('g:00 a')]++;
123
                            if ($createdAt != $updatedAt) {
124
                                $createdModifiedHistogram[HISTOGRAM_MODIFIED][$updatedAt->format('g:00 a')]++;
125
                            }
126
127
                            // tally lead time on the assignment
128
                            $leadTimeTally += strtotime($assignment['due_at']) - strtotime($assignment['created_at']);
129
130
                            // was the assignment created after it was due?
131
                            if (strtotime($assignment['due_at']) < strtotime($assignment['created_at'])) {
132
                                $statistic['created_after_due_count']++;
133
                            }
134
135
                            // ignore ungraded assignments
136
                            if ($assignment['grading_type'] != 'not_graded') {
137
                                $statistic['gradeable_assignment_count']++;
138
                                $hasBeenGraded = false;
139
140
                                // tally zero point assignments
141
                                if ($assignment['points_possible'] == '0') {
142
                                    $statistic['zero_point_assignment_count']++;
143
                                }
144
145
                                // build submission statistic
146
                                $submissions = $api->get(
147
                                    "/courses/{$course['id']}/assignments/{$assignment['id']}/submissions"
148
                                );
149
                                foreach ($submissions as $submission) {
150
                                    if ($submission['workflow_state'] == 'graded') {
151
                                        if ($hasBeenGraded == false) {
0 ignored issues
show
Coding Style Best Practice introduced by
It seems like you are loosely comparing two booleans. Considering using the strict comparison === instead.

When comparing two booleans, it is generally considered safer to use the strict comparison operator.

Loading history...
152
                                            $hasBeenGraded = true;
153
                                            $statistic['graded_assignment_count']++;
154
                                        }
155
                                        $gradedSubmissionsCount++;
156
                                        $turnAroundTimeTally += max(
157
                                            0,
158
                                            strtotime($submission['graded_at']) - strtotime($assignment['due_at'])
159
                                        );
160
                                    }
161
                                }
162
163
                                if (!$hasBeenGraded) {
164
                                    if (array_key_exists('oldest_ungraded_assignment_due_date', $statistic)) {
165
                                        if (strtotime($assignment['due_at']) < strtotime($statistic['oldest_ungraded_assignment_due_date'])) {
166
                                            $statistic['oldest_ungraded_assignment_due_date'] = $assignment['due_at'];
167
                                            $statistic['oldest_ungraded_assignment_url'] = $assignment['html_url'];
168
                                            $statistic['oldest_ungraded_assignment_name'] = $assignment['name'];
169
                                        }
170
                                    } else {
171
                                        $statistic['oldest_ungraded_assignment_due_date'] = $assignment['due_at'];
172
                                        $statistic['oldest_ungraded_assignment_url'] = $assignment['html_url'];
173
                                        $statistic['oldest_ungraded_assignment_name'] = $assignment['name'];
174
                                    }
175
                                }
176
                            }
177
                        } else {
178
                            $statistic['dateless_assignment_count']++;
179
                        }
180
                    }
181
                }
182
183
                $statistic['created_modified_histogram'] = serialize($createdModifiedHistogram);
184
185
                // calculate average submissions graded per assignment (if non-zero)
186
                if ($statistic['gradeable_assignment_count'] && $statistic['student_count']) {
187
                    $statistic['average_submissions_graded'] = $gradedSubmissionsCount / ($statistic['gradeable_assignment_count'] * $statistic['student_count']);
188
                }
189
190
                // calculate the average lead-time on assignments
191
                if ($statistic['assignments_due_count']) {
192
                    $statistic['average_assignment_lead_time'] = $leadTimeTally / $statistic['assignments_due_count'] / 60 / 60 / 24;
193
                }
194
195
                // calculate average grading turn-around per submission
196
                if ($gradedSubmissionsCount) {
197
                    $statistic['average_grading_turn_around'] = $turnAroundTimeTally / $gradedSubmissionsCount / 60 / 60 / 24;
198
                }
199
200
                $query = "INSERT INTO `course_statistics`";
201
                $fields = array();
202
                $values = array();
203
                while (list($field, $value) = each($statistic)) {
204
                    $fields[] = $field;
205
                    $values[] = $value;
206
                }
207
                $query .= ' (`' . implode('`, `', $fields) . "`) VALUES ('" . implode("', '", $values) . "')";
208
                $result = $sql->query($query);
0 ignored issues
show
Unused Code introduced by
$result is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
209
                /* displayError(
0 ignored issues
show
Unused Code Comprehensibility introduced by
57% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
210
                    array(
211
                        'gradedSubmissionsCount' => $gradedSubmissionsCount,
212
                        'turnAroundTimeTally' => $turnAroundTimeTally,
213
                        'statistic' => $statistic,
214
                        'query' => $query,
215
                        'result' => $result
216
                    ),
217
                    true
218
                ); */
219
            }
220
        }
221
    }
222
}
223
224
//debugFlag('START');
225
226
/* create an API connector if not already extant */
227
if (empty($api)) {
228
    $api = new CanvasPest($metadata['CANVAS_API_URL'], $metadata['CANVAS_API_TOKEN']);
229
}
230
231
/* collect data on terms currently in session */
232
$terms = $api->get('accounts/1/terms');
233
$now = strtotime('now');
234
foreach ($terms['enrollment_terms'] as $term) {
235
    if (isset($term['start_at']) && isset($term['end_at'])) {
236
        if ((strtotime($term['start_at']) <= $now) && ($now <= strtotime($term['end_at']))) {
237
            collectStatistics($term['id'], $api, $sql, $metadata);
238
        }
239
    }
240
}
241
242
/* check to see if this data collection has been scheduled. If it hasn't,
243
   schedule it to run nightly. */
244
/* thank you http://stackoverflow.com/a/4421284 ! */
245
$crontab = DATA_COLLECTION_CRONTAB . ' ' . realpath('.') . '/data-collection.sh';
246
$crontabs = shell_exec('crontab -l');
247
if (strpos($crontabs, $crontab) === false) {
248
    $filename = md5(time()) . '.txt';
249
    file_put_contents("/tmp/$filename", $crontabs . $crontab . PHP_EOL);
250
    shell_exec("crontab /tmp/$filename");
251
    debugFlag("added new scheduled data-collection to crontab");
252
}
253
254
//debugFlag('FINISH');
255