Completed
Push — master ( e0a519...eabd41 )
by Julito
119:58 queued 99:23
created

getQuarter()   C

Complexity

Conditions 14
Paths 26

Size

Total Lines 32
Code Lines 25

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 14
eloc 25
nc 26
nop 1
dl 0
loc 32
rs 5.0864
c 0
b 0
f 0

How to fix   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
/* For licensing terms, see /license.txt */
3
/**
4
 * Create course sessions procedure. It creates sessions for courses that haven't it yet.
5
 * If today is greater than OFFSET, it will create them also for the next quarter.
6
 *
7
 * @package chamilo.cron
8
 *
9
 * @author Imanol Losada <[email protected]>
10
 */
11
12
/**
13
 * Initialization.
14
 */
15
if (php_sapi_name() != 'cli') {
16
    exit; //do not run from browser
17
}
18
19
require_once __DIR__."/../inc/global.inc.php";
20
21
// First day of the current month to create sessions and add courses for the next month (e.g. "07")
22
define("OFFSET", "15");
23
/**
24
 * If no $initialDate is supplied, returns an array with the first and last days of the current
25
 * month. Otherwise, returns an array with the first and last days of the $initialDate month .
26
 *
27
 * @param array $initialDate First day of the month
28
 *
29
 * @return array First and last days of the month
30
 */
31
function getMonthFirstAndLastDates($initialDate = null)
32
{
33
    $startDate = $initialDate ? $initialDate : date("Y-m-01");
34
    $nextMonthStartDate = date("Y-m-d", api_strtotime($startDate." + 1 month"));
0 ignored issues
show
Bug introduced by
Are you sure $startDate of type string|array can be used in concatenation? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

34
    $nextMonthStartDate = date("Y-m-d", api_strtotime(/** @scrutinizer ignore-type */ $startDate." + 1 month"));
Loading history...
35
    $endDate = date("Y-m-d", api_strtotime($nextMonthStartDate." - 1 minute"));
36
37
    return ['startDate' => $startDate, 'endDate' => $endDate];
38
}
39
40
/**
41
 * Same as month, but for quarters.
42
 *
43
 * @param array $initialDate First day of the quarter
44
 *
45
 * @return array First and last days of the quarter
46
 */
47
function getQuarterFirstAndLastDates($initialDate = null)
48
{
49
    $startDate = $initialDate ? $initialDate : date("Y-m-01");
50
    $month = getQuarterFirstMonth(getQuarter(date('m', $startDate)));
51
    $startDate = substr($startDate, 0, 5).$month.'-01';
0 ignored issues
show
Bug introduced by
It seems like $startDate can also be of type array; however, parameter $string of substr() does only seem to accept string, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

51
    $startDate = substr(/** @scrutinizer ignore-type */ $startDate, 0, 5).$month.'-01';
Loading history...
52
    $nextQuarterStartDate = date('Y-m-d', api_strtotime($startDate.' + 3 month'));
53
    $endDate = date('Y-m-d', api_strtotime($nextQuarterStartDate.' - 1 minute'));
54
55
    return ['startDate' => $startDate, 'endDate' => $endDate];
56
}
57
58
/**
59
 * Returns a quarter from a month.
60
 *
61
 * @param   string  The month (digit), with or without leading 0
62
 * @param string $month
63
 *
64
 * @return int The yearly quarter (1, 2, 3 or 4) in which this month lies
65
 */
66
function getQuarter($month)
67
{
68
    $quarter = 1;
69
    // Remove the leading 0 if any
70
    if (substr($month, 0, 1) == '0') {
71
        $month = substr($month, 1);
72
    }
73
    // reduce to 4 quarters: 1..3=1; 4..6=2
74
    switch ($month) {
75
        case 1:
76
        case 2:
77
        case 3:
78
            $quarter = 1;
79
            break;
80
        case 4:
81
        case 5:
82
        case 6:
83
            $quarter = 2;
84
            break;
85
        case 7:
86
        case 8:
87
        case 9:
88
            $quarter = 3;
89
            break;
90
        case 10:
91
        case 11:
92
        case 12:
93
            $quarter = 4;
94
            break;
95
    }
96
97
    return $quarter;
98
}
99
100
/**
101
 * Returns the first month of the quarter.
102
 *
103
 * @param   int Quarter
104
 * @param int $quarter
105
 *
106
 * @return string Number of the month, with leading 0
107
 */
108
function getQuarterFirstMonth($quarter)
109
{
110
    switch ($quarter) {
111
        case 1:
112
            return '01';
113
        case 2:
114
            return '04';
115
        case 3:
116
            return '07';
117
        case 4:
118
            return '10';
119
    }
120
121
    return false;
0 ignored issues
show
Bug Best Practice introduced by
The expression return false returns the type false which is incompatible with the documented return type string.
Loading history...
122
}
123
124
/**
125
 * Get the quarter in Roman letters.
126
 *
127
 * @param   int Quarter
128
 * @param int $quarter
129
 *
130
 * @return string Roman letters
131
 */
132
function getQuarterRoman($quarter)
133
{
134
    switch ($quarter) {
135
        case 1:
136
            return 'I';
137
        case 2:
138
            return 'II';
139
        case 3:
140
            return 'III';
141
        case 4:
142
            return 'IV';
143
    }
144
}
145
146
/**
147
 * Creates one session per course with $administratorId as the creator and
148
 * adds it to the session starting on $startDate and finishing on $endDate.
149
 *
150
 * @param array $courses         Courses
151
 * @param int   $administratorId Administrator id
152
 * @param date  $startDate       First day of the month
153
 * @param date  $endDate         Last day of the month
154
 */
155
function createCourseSessions($courses, $administratorId, $startDate, $endDate)
156
{
157
    echo "\n";
158
    echo $courses ?
159
        "Creating sessions and adding courses for the period between ".$startDate." and ".$endDate : "Every course is already in session for the period between ".$startDate." and ".$endDate;
160
    echo "\n=====================================================================================\n\n";
161
    // Loop through courses creating one session per each and adding them
162
    foreach ($courses as $course) {
163
        //$period = date("m/Y", api_strtotime($startDate));
164
        $month = date("m", api_strtotime($startDate));
165
        $year = date("Y", api_strtotime($startDate));
166
        $quarter = getQuarter($month);
167
        $quarter = getQuarterRoman($quarter);
168
        $period = $year.'-'.$quarter;
169
        $sessionName = '['.$period.'] '.$course['title'];
170
        $sessionId = SessionManager::create_session(
171
            $sessionName,
172
            $startDate,
173
            $endDate,
174
            null,
175
            null,
176
            null,
177
            null,
178
            $administratorId,
179
            0,
180
            SESSION_INVISIBLE
181
        );
182
        SessionManager::add_courses_to_session($sessionId, [$course['id']]);
0 ignored issues
show
Bug introduced by
It seems like $sessionId can also be of type false and string; however, parameter $sessionId of SessionManager::add_courses_to_session() does only seem to accept integer, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

182
        SessionManager::add_courses_to_session(/** @scrutinizer ignore-type */ $sessionId, [$course['id']]);
Loading history...
183
        echo "Session '".$sessionName."' created.\nCourse '".$course['title']."' added.\n\n";
184
    }
185
}
186
187
// Starts the script
188
echo "Starting process...".PHP_EOL;
189
// Get first active administrator
190
$administrators = array_reverse(UserManager::get_all_administrators());
191
$lastingAdministrators = count($administrators);
192
while (!$administrators[$lastingAdministrators - 1]['active'] && $lastingAdministrators > 0) {
193
    $lastingAdministrators--;
194
}
195
if (!$lastingAdministrators) {
196
    echo "There are no active administrators. Process halted.\n";
197
    exit;
198
}
199
$administratorId = intval($administrators[$lastingAdministrators - 1]['user_id']);
200
201
// Creates course sessions for the current month
202
$dates = getQuarterFirstAndLastDates(date('Y-m-').'01');
203
// Get courses that don't have any session
204
$courses = CourseManager::getCoursesWithoutSession($dates['startDate'], $dates['endDate']);
205
createCourseSessions($courses, $administratorId, $dates['startDate'], $dates['endDate']);
206
207
// Creates course sessions for the following month
208
$offsetDay = intval(substr($dates['endDate'], 8, 2)) - OFFSET;
209
if (date("Y-m-d") >= date(substr($dates['endDate'], 0, 8).$offsetDay)) {
210
    $dates = getQuarterFirstAndLastDates(date("Y-m-d", api_strtotime(date("Y-m-01")." + 3 month")));
211
    // Get courses that don't have any session the next month
212
    $courses = CourseManager::getCoursesWithoutSession($dates['startDate'], $dates['endDate']);
213
    createCourseSessions($courses, $administratorId, $dates['startDate'], $dates['endDate']);
214
}
215