Completed
Push — master ( 067f55...e1cb48 )
by Julito
09:39
created

StudentFollowUpPlugin::getPermissions()   F

Complexity

Conditions 18
Paths 388

Size

Total Lines 78
Code Lines 50

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 18
eloc 50
nc 388
nop 2
dl 0
loc 78
rs 1.6833
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
2
/* For licensing terms, see /license.txt */
3
4
use Chamilo\CoreBundle\Entity\SessionRelCourseRelUser;
5
use Symfony\Component\Filesystem\Filesystem;
6
7
/**
8
 * Class StudentFollowUpPlugin.
9
 */
10
class StudentFollowUpPlugin extends Plugin
11
{
12
    public $hasEntity = true;
13
14
    /**
15
     * StudentFollowUpPlugin constructor.
16
     */
17
    protected function __construct()
18
    {
19
        parent::__construct(
20
            '0.1',
21
            'Julio Montoya',
22
            [
23
                'tool_enable' => 'boolean',
24
            ]
25
        );
26
    }
27
28
    /**
29
     * @return StudentFollowUpPlugin
30
     */
31
    public static function create()
32
    {
33
        static $result = null;
34
35
        return $result ? $result : $result = new self();
36
    }
37
38
    public function install()
39
    {
40
        $pluginEntityPath = $this->getEntityPath();
41
        if (!is_dir($pluginEntityPath)) {
42
            if (!is_writable(dirname($pluginEntityPath))) {
43
                $message = get_lang('ErrorCreatingDir').': '.$pluginEntityPath;
44
                Display::addFlash(Display::return_message($message, 'error'));
45
46
                return false;
47
            }
48
            mkdir($pluginEntityPath, api_get_permissions_for_new_directories());
49
        }
50
51
        $fs = new Filesystem();
52
        $fs->mirror(__DIR__.'/Entity/', $pluginEntityPath, null, ['override']);
53
        $schema = Database::getManager()->getConnection()->getSchemaManager();
54
55
        if ($schema->tablesExist('sfu_post') === false) {
56
            $sql = "CREATE TABLE IF NOT EXISTS sfu_post (id INT AUTO_INCREMENT NOT NULL, insert_user_id INT NOT NULL, user_id INT NOT NULL, parent_id INT DEFAULT NULL, title VARCHAR(255) NOT NULL, content LONGTEXT DEFAULT NULL, external_care_id VARCHAR(255) DEFAULT NULL, created_at DATETIME DEFAULT NULL, updated_at DATETIME DEFAULT NULL, private TINYINT(1) NOT NULL, external_source TINYINT(1) NOT NULL, tags LONGTEXT NOT NULL COMMENT '(DC2Type:array)', attachment VARCHAR(255) NOT NULL, lft INT DEFAULT NULL, rgt INT DEFAULT NULL, lvl INT DEFAULT NULL, root INT DEFAULT NULL, INDEX IDX_35F9473C9C859CC3 (insert_user_id), INDEX IDX_35F9473CA76ED395 (user_id), INDEX IDX_35F9473C727ACA70 (parent_id), PRIMARY KEY(id)) DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci ENGINE = InnoDB;";
57
            Database::query($sql);
58
            $sql = "ALTER TABLE sfu_post ADD CONSTRAINT FK_35F9473C9C859CC3 FOREIGN KEY (insert_user_id) REFERENCES user (id);";
59
            Database::query($sql);
60
            $sql = "ALTER TABLE sfu_post ADD CONSTRAINT FK_35F9473CA76ED395 FOREIGN KEY (user_id) REFERENCES user (id);";
61
            Database::query($sql);
62
            $sql = "ALTER TABLE sfu_post ADD CONSTRAINT FK_35F9473C727ACA70 FOREIGN KEY (parent_id) REFERENCES sfu_post (id) ON DELETE SET NULL;";
63
            Database::query($sql);
64
        }
65
    }
66
67
    public function uninstall()
68
    {
69
        $pluginEntityPath = $this->getEntityPath();
70
        $fs = new Filesystem();
71
        if ($fs->exists($pluginEntityPath)) {
72
            $fs->remove($pluginEntityPath);
73
        }
74
        $table = Database::get_main_table('sfu_post');
75
        $sql = "DROP TABLE IF EXISTS $table";
76
        Database::query($sql);
77
    }
78
79
    /**
80
     * @return string
81
     */
82
    public function getEntityPath()
83
    {
84
        return api_get_path(SYS_PATH).'src/Chamilo/PluginBundle/Entity/'.$this->getCamelCaseName();
85
    }
86
87
    /**
88
     * @param int $studentId
89
     * @param int $currentUserId
90
     *
91
     * @return array
92
     */
93
    public static function getPermissions($studentId, $currentUserId)
94
    {
95
        $params = ['variable = ? AND subkey = ?' => ['status', 'studentfollowup']];
96
        $result = api_get_settings_params_simple($params);
97
        $installed = false;
98
        if (!empty($result) && $result['selected_value'] === 'installed') {
99
            $installed = true;
100
        }
101
102
        if ($installed == 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...
103
            return [
104
                'is_allow' => false,
105
                'show_private' => false,
106
            ];
107
        }
108
109
        if ($studentId === $currentUserId) {
110
            $isAllow = true;
111
            $showPrivate = true;
112
        } else {
113
            $isDrh = api_is_drh();
114
            $isCareTaker = false;
115
            $isDrhRelatedViaPost = false;
116
            $isCourseCoach = false;
117
            $isDrhRelatedToSession = false;
118
119
            // Only admins and DRH that follow the user
120
            $isAdmin = api_is_platform_admin();
121
122
            // Check if user is care taker
123
            if ($isDrh) {
124
                $criteria = [
125
                    'user' => $studentId,
126
                    'insertUser' => $currentUserId,
127
                ];
128
                $repo = Database::getManager()->getRepository('ChamiloPluginBundle:StudentFollowUp\CarePost');
129
                $post = $repo->findOneBy($criteria);
130
                if ($post) {
131
                    $isDrhRelatedViaPost = true;
132
                }
133
            }
134
135
            // Check if course session coach
136
            $sessions = SessionManager::get_sessions_by_user($studentId);
137
            if (!empty($sessions)) {
138
                foreach ($sessions as $session) {
139
                    $sessionId = $session['session_id'];
140
                    $sessionDrhInfo = SessionManager::getSessionFollowedByDrh(
141
                        $currentUserId,
142
                        $sessionId
143
                    );
144
                    if (!empty($sessionDrhInfo)) {
145
                        $isDrhRelatedToSession = true;
146
                        break;
147
                    }
148
                    foreach ($session['courses'] as $course) {
149
                        //$isCourseCoach = api_is_coach($sessionId, $course['real_id']);
150
                        $coachList = SessionManager::getCoachesByCourseSession(
151
                            $sessionId,
152
                            $course['real_id']
153
                        );
154
                        if (!empty($coachList) && in_array($currentUserId, $coachList)) {
155
                            $isCourseCoach = true;
156
                            break 2;
157
                        }
158
                    }
159
                }
160
            }
161
162
            $isCareTaker = $isDrhRelatedViaPost && $isDrhRelatedToSession;
163
164
            $isAllow = $isAdmin || $isCareTaker || $isDrhRelatedToSession || $isCourseCoach;
165
            $showPrivate = $isAdmin || $isCareTaker;
166
        }
167
168
        return [
169
            'is_allow' => $isAllow,
170
            'show_private' => $showPrivate,
171
        ];
172
    }
173
174
    /**
175
     * @param string $status
176
     * @param int    $currentUserId
177
     * @param int    $start
178
     * @param int    $limit
179
     *
180
     * @return array
181
     */
182
    public static function getUsers($status, $currentUserId, $start, $limit)
183
    {
184
        switch ($status) {
185
            case COURSEMANAGER:
186
                $sessions = SessionManager::get_sessions_by_user($currentUserId);
187
                $sessions = array_column($sessions, 'session_id');
188
189
                // Get session courses where I'm coach
190
                $courseList = SessionManager::getCoursesListByCourseCoach($currentUserId);
191
                $courses = [];
192
                /** @var SessionRelCourseRelUser $courseItem */
193
                foreach ($courseList as $courseItem) {
194
                    $courses[] = $courseItem->getCourse()->getId();
195
                }
196
                break;
197
            case DRH:
198
                $sessions = SessionManager::get_sessions_followed_by_drh($currentUserId);
199
                $sessions = array_column($sessions, 'id');
200
                $courses = [];
201
                foreach ($sessions as $sessionId) {
202
                    $sessionDrhInfo = SessionManager::getSessionFollowedByDrh(
203
                        $currentUserId,
204
                        $sessionId
205
                    );
206
                    if ($sessionDrhInfo && isset($sessionDrhInfo['course_list'])) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $sessionDrhInfo 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...
207
                        $courses = array_merge($courses, array_column($sessionDrhInfo['course_list'], 'id'));
208
                    }
209
                }
210
                break;
211
        }
212
213
        $userList = SessionManager::getUsersByCourseAndSessionList(
214
            $sessions,
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $sessions does not seem to be defined for all execution paths leading up to this point.
Loading history...
215
            $courses,
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $courses does not seem to be defined for all execution paths leading up to this point.
Loading history...
216
            $start,
217
            $limit
218
        );
219
220
        /*$userList = [];
221
        foreach ($sessions as $sessionId) {
222
            foreach ($courses as $courseId) {
223
                $courseInfo = ['real_id' => $courseId];
224
                $userFromSessionList = SessionManager::getUsersByCourseSession(
225
                    $sessionId,
226
                    $courseInfo
227
                );
228
                $userList = array_merge($userList, $userFromSessionList);
229
            }
230
            $userList = array_unique($userList);
231
        }*/
232
233
        return $userList;
234
    }
235
236
    /**
237
     * @return int
238
     */
239
    public static function getPageSize()
240
    {
241
        return 20;
242
    }
243
244
    /**
245
     * @param int $userId
246
     */
247
    public function doWhenDeletingUser($userId)
248
    {
249
        $userId = (int) $userId;
250
251
        Database::query("DELETE FROM sfu_post WHERE user_id = $userId");
252
        Database::query("DELETE FROM sfu_post WHERE insert_user_id = $userId");
253
    }
254
}
255