Passed
Push — 1.11.x ( 94cf83...944136 )
by Julito
12:48 queued 13s
created

PauseTraining::updateUserPauseTraining()   B

Complexity

Conditions 9
Paths 34

Size

Total Lines 63
Code Lines 37

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 9
eloc 37
c 1
b 0
f 0
nc 34
nop 2
dl 0
loc 63
rs 7.7724

How to fix   Long Method   

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
class PauseTraining extends Plugin
6
{
7
    public $isCoursePlugin = false;
8
9
    protected function __construct()
10
    {
11
        parent::__construct(
12
            '0.1',
13
            'Julio Montoya',
14
            [
15
                'tool_enable' => 'boolean',
16
                'allow_users_to_edit_pause_formation' => 'boolean',
17
                'cron_alert_users_if_inactive_days' => 'text', // Example: "5" or "5,10,15"
18
            ]
19
        );
20
    }
21
22
    public static function create()
23
    {
24
        static $result = null;
25
26
        return $result ? $result : $result = new self();
27
    }
28
29
    public function updateUserPauseTraining($userId, $values)
30
    {
31
        $userInfo = api_get_user_info($userId);
32
        if (empty($userInfo)) {
33
            throw new Exception("User #$userId does not exists");
34
        }
35
36
        $variables = [
37
            'pause_formation',
38
            'start_pause_date',
39
            'end_pause_date',
40
            'allow_notifications',
41
        ];
42
43
        $valuesToUpdate = [
44
            'item_id' => $userId,
45
        ];
46
47
        // Check if variables exist.
48
        foreach ($variables as $variable) {
49
            if (!isset($values[$variable])) {
50
                throw new Exception("Variable '$variable' is missing. Cannot updated.");
51
            }
52
53
            $valuesToUpdate['extra_'.$variable] = $values[$variable];
54
        }
55
56
        // Clean variables
57
        $pause = (int) $valuesToUpdate['extra_pause_formation'];
58
        if (empty($pause)) {
59
            $valuesToUpdate['extra_pause_formation'] = 0;
60
        } else {
61
            $valuesToUpdate['extra_pause_formation'] = [];
62
            $valuesToUpdate['extra_pause_formation']['extra_pause_formation'] = $pause;
63
        }
64
65
        $notification = (int) $valuesToUpdate['extra_allow_notifications'];
66
        if (empty($notification)) {
67
            $valuesToUpdate['extra_allow_notifications'] = 0;
68
        } else {
69
            $valuesToUpdate['extra_allow_notifications'] = [];
70
            $valuesToUpdate['extra_allow_notifications']['extra_allow_notifications'] = $notification;
71
        }
72
73
        $check = DateTime::createFromFormat('Y-m-d H:i', $valuesToUpdate['extra_start_pause_date']);
74
75
        if (false === $check) {
76
            throw new Exception("start_pause_date is not valid date time format should be: Y-m-d H:i");
77
        }
78
79
        $check = DateTime::createFromFormat('Y-m-d H:i', $valuesToUpdate['extra_end_pause_date']);
80
        if (false === $check) {
81
            throw new Exception("end_pause_date is not valid date time format should be: Y-m-d H:i");
82
        }
83
84
        if (api_strtotime($valuesToUpdate['extra_start_pause_date']) > api_strtotime($valuesToUpdate['extra_end_pause_date'])) {
85
            throw new Exception("end_pause_date must be bigger than start_pause_date");
86
        }
87
88
        $extraField = new ExtraFieldValue('user');
89
        $extraField->saveFieldValues($valuesToUpdate, true, false, [], [], true);
90
91
        return (int) $userId;
92
    }
93
94
    public function runCron()
95
    {
96
        $enable = $this->get('tool_enable');
97
        $enableDays = $this->get('cron_alert_users_if_inactive_days');
98
99
        if ($enable && !empty($enableDays)) {
100
            $enableDaysList = explode(',', $enableDays);
101
            rsort($enableDaysList);
102
103
            $loginTable = Database::get_main_table(TABLE_STATISTIC_TRACK_E_COURSE_ACCESS);
104
            $userTable = Database::get_main_table(TABLE_MAIN_USER);
105
            $now = api_get_utc_datetime();
106
            $usersNotificationPerDay = [];
107
            $users = [];
108
            foreach ($enableDaysList as $day) {
109
                $day = (int) $day;
110
111
                $sql = "SELECT
112
                        stats_login.user_id,
113
                        MAX(stats_login.login_course_date) max_date
114
                        FROM $loginTable stats_login
115
                        INNER JOIN $userTable u
116
                        ON (u.id = stats_login.user_id)
117
                        WHERE
118
                            u.status <> ".ANONYMOUS." AND
119
                            u.active = 1
120
                        GROUP BY stats_login.user_id
121
                        HAVING DATE_SUB('$now', INTERVAL '$day' DAY) > max_date ";
122
123
                $rs = Database::query($sql);
124
                while ($user = Database::fetch_array($rs)) {
125
                    $userId = $user['user_id'];
126
127
                    if (in_array($userId, $users)) {
128
                        continue;
129
                    }
130
                    $users[] = $userId;
131
                    $usersNotificationPerDay[$day][] = $userId;
132
                }
133
            }
134
            $usersNotificationPerDay[5][] = 1;
135
136
            if (!empty($usersNotificationPerDay)) {
137
                ksort($usersNotificationPerDay);
138
                $extraFieldValue = new ExtraFieldValue('user');
139
                foreach ($usersNotificationPerDay as $day => $userList) {
140
                    $template = new Template();
141
                    // @todo check email format
142
                    $title  = sprintf($this->get_lang('NotificationXDays'), $day);
143
144
                    foreach ($userList as $userId) {
145
                        $userInfo = api_get_user_info($userId);
146
                        $pause = $extraFieldValue->get_values_by_handler_and_field_variable($userId, 'pause_formation');
147
                        if (!empty($pause) && isset($pause['value']) && 1 == $pause['value']) {
148
                            // Skip user because he paused his formation.
149
                            continue;
150
                        }
151
152
                        $template->assign('days', $day);
153
                        $template->assign('user', $userInfo);
154
                        $content = $template->fetch('pausetraining/view/notification_content.tpl');
155
                        //MessageManager::send_message($userId, $title, $content);
156
                    }
157
158
                }
159
            }
160
        }
161
    }
162
163
    public function install()
164
    {
165
        UserManager::create_extra_field(
166
            'pause_formation',
167
            ExtraField::FIELD_TYPE_CHECKBOX,
168
            $this->get_lang('PauseFormation'),
169
            ''
170
        );
171
172
        UserManager::create_extra_field(
173
            'start_pause_date',
174
            ExtraField::FIELD_TYPE_DATETIME,
175
            $this->get_lang('StartPauseDateTime'),
176
            ''
177
        );
178
179
        UserManager::create_extra_field(
180
            'end_pause_date',
181
            ExtraField::FIELD_TYPE_DATETIME,
182
            $this->get_lang('EndPauseDateTime'),
183
            ''
184
        );
185
186
        UserManager::create_extra_field(
187
            'allow_notifications',
188
            ExtraField::FIELD_TYPE_CHECKBOX,
189
            $this->get_lang('AllowEmailNotification'),
190
            ''
191
        );
192
    }
193
194
    public function uninstall()
195
    {
196
    }
197
}
198