Completed
Push — master ( f7fcbb...abc4a6 )
by Seth
05:40 queued 02:51
created

data-collection.php ➔ hoursRange()   B

Complexity

Conditions 6
Paths 12

Size

Total Lines 24
Code Lines 12

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 6
eloc 12
nc 12
nop 6
dl 0
loc 24
rs 8.5125
c 0
b 0
f 0
1
#!/usr/bin/env 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 4 and the first side effect is on line 1.

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
<?php
3
4
define('IGNORE_UI', true);
5
6
require_once __DIR__ . '/../common.inc.php';
7
require_once __DIR__ . '/../constants.inc.php';
8
9
use smtech\GradingAnalytics\Toolbox;
10
use smtech\CanvasPest\CanvasPest;
11
12
// http://stackoverflow.com/a/21896310
13
function hoursRange($lower = 0, $upper = 86400, $step = 3600, $keyFormat = '', $value = '', $valueIsFormat = false)
14
{
15
    $times = array();
16
17
    if (empty( $value ) && $valueIsFormat) {
18
        $value = 'g:i a';
19
    }
20
21
    if (empty($keyFormat)) {
22
        $keyFormat = 'g:i a';
23
    }
24
25
    foreach (range( $lower, $upper, $step ) as $increment) {
26
        $increment = gmdate( $keyFormat, $increment );
27
28
        list( $hour, $minutes ) = explode( ':', $increment );
29
30
        $date = new DateTime( $hour . ':' . $minutes );
31
32
        $times[(string) $increment] = ($valueIsFormat ? $date->format( $value ) : $value);
33
    }
34
35
    return $times;
36
}
37
38
function collectStatistics($term, Toolbox $toolbox)
0 ignored issues
show
Coding Style introduced by
collectStatistics uses the super-global variable $_SESSION which is generally not recommended.

Instead of super-globals, we recommend to explicitly inject the dependencies of your class. This makes your code less dependent on global state and it becomes generally more testable:

// Bad
class Router
{
    public function generate($path)
    {
        return $_SERVER['HOST'].$path;
    }
}

// Better
class Router
{
    private $host;

    public function __construct($host)
    {
        $this->host = $host;
    }

    public function generate($path)
    {
        return $this->host.$path;
    }
}

class Controller
{
    public function myAction(Request $request)
    {
        // Instead of
        $page = isset($_GET['page']) ? intval($_GET['page']) : 1;

        // Better (assuming you use the Symfony2 request)
        $page = $request->query->get('page', 1);
    }
}
Loading history...
39
{
40
    /*
41
     * TODO make this configurable -- I've hard-coded in the root of our
42
     * Academics sub-account, which contains all of our departmental
43
     * sub-accounts. This account ID _could_ be collected via the account
44
     * navigation link (which conveys the account ID)
45
     */
46
    $courses = $toolbox->api_get(
47
        '/accounts/132/courses',
48
        array(
49
            'with_enrollments' => 'true',
50
            'enrollment_term_id' => $term
51
        )
52
    );
53
54
    // so that everything has a consistent benchmark
55
    $timestamp = time();
56
57
    foreach ($courses as $course) {
0 ignored issues
show
Bug introduced by
The expression $courses of type object<smtech\CanvasPest...CanvasPest\CanvasArray> is not guaranteed to be traversable. How about adding an additional type check?

There are different options of fixing this problem.

  1. If you want to be on the safe side, you can add an additional type-check:

    $collection = json_decode($data, true);
    if ( ! is_array($collection)) {
        throw new \RuntimeException('$collection must be an array.');
    }
    
    foreach ($collection as $item) { /** ... */ }
    
  2. If you are sure that the expression is traversable, you might want to add a doc comment cast to improve IDE auto-completion and static analysis:

    /** @var array $collection */
    $collection = json_decode($data, true);
    
    foreach ($collection as $item) { /** .. */ }
    
  3. Mark the issue as a false-positive: Just hover the remove button, in the top-right corner of this issue for more options.

Loading history...
58
        $statistic = array(
59
            'timestamp' => date(DATE_ISO8601, $timestamp),
60
            'course[id]' => $course['id'],
61
            'course[name]' => $course['name'],
62
            'course[account_id]' => $course['account_id'],
63
            'gradebook_url' => $_SESSION[CANVAS_INSTANCE_URL] . "/courses/{$course['id']}/gradebook2",
64
            'assignments_due_count' => 0,
65
            'dateless_assignment_count' => 0,
66
            'created_after_due_count' => 0,
67
            'gradeable_assignment_count' => 0,
68
            'graded_assignment_count' => 0,
69
            'zero_point_assignment_count' => 0
70
        );
71
72
        $teacherIds = array();
73
        $teacherNames = array();
74
        $teachers = $toolbox->api_get(
75
            "/courses/{$course['id']}/enrollments",
76
            array(
77
                'type[]' => 'TeacherEnrollment'
78
            )
79
        );
80
        foreach ($teachers as $teacher) {
0 ignored issues
show
Bug introduced by
The expression $teachers of type object<smtech\CanvasPest...CanvasPest\CanvasArray> is not guaranteed to be traversable. How about adding an additional type check?

There are different options of fixing this problem.

  1. If you want to be on the safe side, you can add an additional type-check:

    $collection = json_decode($data, true);
    if ( ! is_array($collection)) {
        throw new \RuntimeException('$collection must be an array.');
    }
    
    foreach ($collection as $item) { /** ... */ }
    
  2. If you are sure that the expression is traversable, you might want to add a doc comment cast to improve IDE auto-completion and static analysis:

    /** @var array $collection */
    $collection = json_decode($data, true);
    
    foreach ($collection as $item) { /** .. */ }
    
  3. Mark the issue as a false-positive: Just hover the remove button, in the top-right corner of this issue for more options.

Loading history...
81
            $teacherIds[] = $teacher['user']['id'];
82
            $teacherNames[] = $teacher['user']['sortable_name'];
83
        }
84
        $statistic['teacher[id]s'] = serialize($teacherIds);
85
        $statistic['teacher[sortable_name]s'] = serialize($teacherNames);
86
87
        $account = $toolbox->api_get("/accounts/{$course['account_id']}");
88
        $statistic['account[name]'] = $account['name'];
89
90
        // ignore classes with no teachers (how do they even exist? weird.)
91
        if (count($teacherIds) != 0) {
92
            $statistic['student_count'] = 0;
93
            $students = $toolbox->api_get(
94
                "/courses/{$course['id']}/enrollments",
95
                array(
96
                    'type[]' => 'StudentEnrollment'
97
                )
98
            );
99
            $statistic['student_count'] = $students->count();
0 ignored issues
show
Bug introduced by
The method count does only exist in smtech\CanvasPest\CanvasArray, but not in smtech\CanvasPest\CanvasObject.

It seems like the method you are trying to call exists only in some of the possible types.

Let’s take a look at an example:

class A
{
    public function foo() { }
}

class B extends A
{
    public function bar() { }
}

/**
 * @param A|B $x
 */
function someFunction($x)
{
    $x->foo(); // This call is fine as the method exists in A and B.
    $x->bar(); // This method only exists in B and might cause an error.
}

Available Fixes

  1. Add an additional type-check:

    /**
     * @param A|B $x
     */
    function someFunction($x)
    {
        $x->foo();
    
        if ($x instanceof B) {
            $x->bar();
        }
    }
    
  2. Only allow a single type to be passed if the variable comes from a parameter:

    function someFunction(B $x) { /** ... */ }
    
Loading history...
100
101
            // ignore classes with no students
102
            if ($statistic['student_count'] != 0) {
103
                $assignments = $toolbox->api_get(
104
                    "/courses/{$course['id']}/assignments"
105
                );
106
107
                $gradedSubmissionsCount = 0;
108
                $turnAroundTimeTally = 0;
109
                $leadTimeTally = 0;
110
                $createdModifiedHistogram = array(
111
                    HISTOGRAM_CREATED => hoursRange(0, 86400, 3600, '', 0),
112
                    HISTOGRAM_MODIFIED => hoursRange(0, 86400, 3600, '', 0)
113
                );
114
115
                foreach ($assignments as $assignment) {
0 ignored issues
show
Bug introduced by
The expression $assignments of type object<smtech\CanvasPest...CanvasPest\CanvasArray> is not guaranteed to be traversable. How about adding an additional type check?

There are different options of fixing this problem.

  1. If you want to be on the safe side, you can add an additional type-check:

    $collection = json_decode($data, true);
    if ( ! is_array($collection)) {
        throw new \RuntimeException('$collection must be an array.');
    }
    
    foreach ($collection as $item) { /** ... */ }
    
  2. If you are sure that the expression is traversable, you might want to add a doc comment cast to improve IDE auto-completion and static analysis:

    /** @var array $collection */
    $collection = json_decode($data, true);
    
    foreach ($collection as $item) { /** .. */ }
    
  3. Mark the issue as a false-positive: Just hover the remove button, in the top-right corner of this issue for more options.

Loading history...
116
                    // ignore unpublished assignments
117
                    if ($assignment['published'] == true) {
118
                        // check for due dates
119
                        $dueDate = new DateTime($assignment['due_at']);
120
                        $dueDate->setTimeZone(new DateTimeZone(SCHOOL_TIME_ZONE));
121
                        if (($timestamp - $dueDate->getTimestamp()) > 0) {
122
                            $statistic['assignments_due_count']++;
123
124
                            // update created_modified_histogram
125
                            $createdAt = new DateTime($assignment['created_at']);
126
                            $createdAt->setTimeZone(new DateTimeZone(SCHOOL_TIME_ZONE));
127
                            $updatedAt = new DateTime($assignment['updated_at']);
128
                            $updatedAt->setTimeZone(new DateTimeZone(SCHOOL_TIME_ZONE));
129
                            $createdModifiedHistogram[HISTOGRAM_CREATED][$createdAt->format('g:00 a')]++;
130
                            if ($createdAt != $updatedAt) {
131
                                $createdModifiedHistogram[HISTOGRAM_MODIFIED][$updatedAt->format('g:00 a')]++;
132
                            }
133
134
                            // tally lead time on the assignment
135
                            $leadTimeTally += strtotime($assignment['due_at']) - strtotime($assignment['created_at']);
136
137
                            // was the assignment created after it was due?
138
                            if (strtotime($assignment['due_at']) < strtotime($assignment['created_at'])) {
139
                                $statistic['created_after_due_count']++;
140
                            }
141
142
                            // ignore ungraded assignments
143
                            if ($assignment['grading_type'] != 'not_graded') {
144
                                $statistic['gradeable_assignment_count']++;
145
                                $hasBeenGraded = false;
146
147
                                // tally zero point assignments
148
                                if ($assignment['points_possible'] == '0') {
149
                                    $statistic['zero_point_assignment_count']++;
150
                                }
151
152
                                // build submission statistic
153
                                $submissions = $toolbox->api_get(
154
                                    "/courses/{$course['id']}/assignments/{$assignment['id']}/submissions"
155
                                );
156
                                foreach ($submissions as $submission) {
0 ignored issues
show
Bug introduced by
The expression $submissions of type object<smtech\CanvasPest...CanvasPest\CanvasArray> is not guaranteed to be traversable. How about adding an additional type check?

There are different options of fixing this problem.

  1. If you want to be on the safe side, you can add an additional type-check:

    $collection = json_decode($data, true);
    if ( ! is_array($collection)) {
        throw new \RuntimeException('$collection must be an array.');
    }
    
    foreach ($collection as $item) { /** ... */ }
    
  2. If you are sure that the expression is traversable, you might want to add a doc comment cast to improve IDE auto-completion and static analysis:

    /** @var array $collection */
    $collection = json_decode($data, true);
    
    foreach ($collection as $item) { /** .. */ }
    
  3. Mark the issue as a false-positive: Just hover the remove button, in the top-right corner of this issue for more options.

Loading history...
157
                                    if ($submission['workflow_state'] == 'graded') {
158
                                        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...
159
                                            $hasBeenGraded = true;
160
                                            $statistic['graded_assignment_count']++;
161
                                        }
162
                                        $gradedSubmissionsCount++;
163
                                        $turnAroundTimeTally += max(
164
                                            0,
165
                                            strtotime($submission['graded_at']) - strtotime($assignment['due_at'])
166
                                        );
167
                                    }
168
                                }
169
170
                                if (!$hasBeenGraded) {
171
                                    if (array_key_exists('oldest_ungraded_assignment_due_date', $statistic)) {
172
                                        if (strtotime($assignment['due_at']) < strtotime($statistic['oldest_ungraded_assignment_due_date'])) {
173
                                            $statistic['oldest_ungraded_assignment_due_date'] = $assignment['due_at'];
174
                                            $statistic['oldest_ungraded_assignment_url'] = $assignment['html_url'];
175
                                            $statistic['oldest_ungraded_assignment_name'] = $assignment['name'];
176
                                        }
177
                                    } else {
178
                                        $statistic['oldest_ungraded_assignment_due_date'] = $assignment['due_at'];
179
                                        $statistic['oldest_ungraded_assignment_url'] = $assignment['html_url'];
180
                                        $statistic['oldest_ungraded_assignment_name'] = $assignment['name'];
181
                                    }
182
                                }
183
                            }
184
                        } else {
185
                            $statistic['dateless_assignment_count']++;
186
                        }
187
                    }
188
                }
189
190
                $statistic['created_modified_histogram'] = serialize($createdModifiedHistogram);
191
192
                // calculate average submissions graded per assignment (if non-zero)
193
                if ($statistic['gradeable_assignment_count'] && $statistic['student_count']) {
194
                    $statistic['average_submissions_graded'] = $gradedSubmissionsCount / ($statistic['gradeable_assignment_count'] * $statistic['student_count']);
195
                }
196
197
                // calculate the average lead-time on assignments
198
                if ($statistic['assignments_due_count']) {
199
                    $statistic['average_assignment_lead_time'] = $leadTimeTally / $statistic['assignments_due_count'] / 60 / 60 / 24;
200
                }
201
202
                // calculate average grading turn-around per submission
203
                if ($gradedSubmissionsCount) {
204
                    $statistic['average_grading_turn_around'] = $turnAroundTimeTally / $gradedSubmissionsCount / 60 / 60 / 24;
205
                }
206
207
                $query = "INSERT INTO `course_statistics`";
208
                $fields = array();
209
                $values = array();
210
                while (list($field, $value) = each($statistic)) {
211
                    $fields[] = $field;
212
                    $values[] = $value;
213
                }
214
                $query .= ' (`' . implode('`, `', $fields) . "`) VALUES ('" . implode("', '", $values) . "')";
215
                $result = $toolbox->mysql_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...
216
            }
217
        }
218
    }
219
}
220
221
/* force API configuration from config file */
222
$toolbox->setApi(new CanvasPest(
223
    $_SESSION[CANVAS_INSTANCE_URL] . '/api/v1',
224
    $toolbox->config(Toolbox::TOOL_CANVAS_API)['token']
225
));
226
227
/* collect data on terms currently in session */
228
try {
229
    $terms = $toolbox->api_get('accounts/1/terms');
230
    $now = strtotime('now');
231
    foreach ($terms['enrollment_terms'] as $term) {
232
        if (isset($term['start_at']) && isset($term['end_at'])) {
233
            if ((strtotime($term['start_at']) <= $now) && ($now <= strtotime($term['end_at']))) {
234
                collectStatistics($term['id'], $toolbox);
235
            }
236
        }
237
    }
238
} catch (Exception $e) {
239
    echo $e->getMessage();
240
}
241