Completed
Pull Request — master (#125)
by
unknown
69:05 queued 67:51
created

Manager   C

Complexity

Total Complexity 54

Size/Duplication

Total Lines 402
Duplicated Lines 2.99 %

Coupling/Cohesion

Components 1
Dependencies 0

Test Coverage

Coverage 88.13%

Importance

Changes 0
Metric Value
wmc 54
lcom 1
cbo 0
dl 12
loc 402
ccs 193
cts 219
cp 0.8813
rs 6.4799
c 0
b 0
f 0

15 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 15 1
B announce() 0 38 6
A addGroupLink() 0 9 1
A delete() 0 20 1
A getGroups() 0 24 5
A markNotificationRead() 0 11 2
A getNumberOfComments() 0 3 1
A hasNotifications() 0 22 3
A removeNotifications() 0 31 2
A parseSubject() 0 3 1
A checkIsAdmin() 0 14 4
A getAdminGroups() 0 5 1
C getAnnouncement() 6 62 13
D getAnnouncements() 6 74 12
A parseMessage() 0 3 1

How to fix   Duplicated Code    Complexity   

Duplicated Code

Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.

Common duplication problems, and corresponding solutions are:

Complex Class

 Tip:   Before tackling complexity, make sure that you eliminate any duplication first. This often can reduce the size of classes significantly.

Complex classes like Manager often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes. You can also have a look at the cohesion graph to spot any un-connected, or weakly-connected components.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

While breaking up the class, it is a good idea to analyze how other classes use Manager, and based on these observations, apply Extract Interface, too.

1
<?php
2
declare(strict_types=1);
3
/**
4
 * @copyright Copyright (c) 2016, Joas Schilling <[email protected]>
5
 *
6
 * @author Joas Schilling <[email protected]>
7
 *
8
 * @license GNU AGPL version 3 or any later version
9
 *
10
 * This program is free software: you can redistribute it and/or modify
11
 * it under the terms of the GNU Affero General Public License as
12
 * published by the Free Software Foundation, either version 3 of the
13
 * License, or (at your option) any later version.
14
 *
15
 * This program is distributed in the hope that it will be useful,
16
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
17
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
18
 * GNU Affero General Public License for more details.
19
 *
20
 * You should have received a copy of the GNU Affero General Public License
21
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
22
 *
23
 */
24
25
namespace OCA\AnnouncementCenter;
26
27
use OCP\BackgroundJob\IJobList;
28
use OCP\Comments\ICommentsManager;
29
use OCP\DB\QueryBuilder\IQueryBuilder;
30
use OCP\IConfig;
31
use OCP\IDBConnection;
32
use OCP\IGroupManager;
33
use OCP\Notification\IManager as INotificationManager;
34
use OCP\IUser;
35
use OCP\IUserSession;
36
37
class Manager {
38
39
	/** @var IConfig */
40
	protected $config;
41
42
	/** @var IDBConnection */
43
	protected $connection;
44
45
	/** @var IGroupManager */
46
	protected $groupManager;
47
48
	/** @var INotificationManager */
49
	protected $notificationManager;
50
51
	/** @var ICommentsManager */
52
	protected $commentsManager;
53
54
	/** @var IJobList */
55
	protected $jobList;
56
57
	/** @var IUserSession */
58
	protected $userSession;
59
60 21
	public function __construct(IConfig $config,
61
								IDBConnection $connection,
62
								IGroupManager $groupManager,
63
								INotificationManager $notificationManager,
64
								ICommentsManager $commentsManager,
65
								IJobList $jobList,
66
								IUserSession $userSession) {
67 21
		$this->config = $config;
68 21
		$this->connection = $connection;
69 21
		$this->groupManager = $groupManager;
70 21
		$this->notificationManager = $notificationManager;
71 21
		$this->commentsManager = $commentsManager;
72 21
		$this->jobList = $jobList;
73 21
		$this->userSession = $userSession;
74 21
	}
75
76
	/**
77
	 * @param string $subject
78
	 * @param string $message
79
	 * @param string $user
80
	 * @param int $time
81
	 * @param string[] $groups
82
	 * @param bool $comments
83
	 * @return array
84
	 * @throws \InvalidArgumentException when the subject is empty or invalid
85
	 */
86 7
	public function announce(string $subject, string $message, string $user, int $time, array $groups, bool$comments): array {
87 7
		$subject = trim($subject);
88 7
		$message = trim($message);
89 7
		if (isset($subject[512])) {
90 1
			throw new \InvalidArgumentException('Invalid subject', 1);
91
		}
92
93 6
		if ($subject === '') {
94 1
			throw new \InvalidArgumentException('Invalid subject', 2);
95
		}
96
97 5
		$queryBuilder = $this->connection->getQueryBuilder();
98 5
		$queryBuilder->insert('announcements')
99 5
			->values([
100 5
				'announcement_time' => $queryBuilder->createNamedParameter($time),
101 5
				'announcement_user' => $queryBuilder->createNamedParameter($user),
102 5
				'announcement_subject' => $queryBuilder->createNamedParameter($subject),
103 5
				'announcement_message' => $queryBuilder->createNamedParameter($message),
104 5
				'allow_comments' => $queryBuilder->createNamedParameter((int) $comments),
105
			]);
106 5
		$queryBuilder->execute();
107
108 5
		$id = $queryBuilder->getLastInsertId();
109
110 5
		$addedGroups = 0;
111 5
		foreach ($groups as $group) {
112 5
			if ($this->groupManager->groupExists($group)) {
113 4
				$this->addGroupLink((int) $id, $group);
114 5
				$addedGroups++;
115
			}
116
		}
117
118 5
		if ($addedGroups === 0) {
119 4
			$this->addGroupLink((int) $id, 'everyone');
120
		}
121
122 5
		return $this->getAnnouncement($id, true, true);
123
	}
124
125 5
	protected function addGroupLink(int $announcementId, string $group) {
126 5
		$query = $this->connection->getQueryBuilder();
127 5
		$query->insert('announcements_groups')
128 5
			->values([
129 5
				'announcement_id' => $query->createNamedParameter($announcementId),
130 5
				'gid' => $query->createNamedParameter($group),
131
			]);
132 5
		$query->execute();
133 5
	}
134
135 5
	public function delete(int $id) {
136
		// Delete notifications
137 5
		$notification = $this->notificationManager->createNotification();
138 5
		$notification->setApp('announcementcenter')
139 5
			->setObject('announcement', $id);
140 5
		$this->notificationManager->markProcessed($notification);
141
142
		// Delete comments
143 5
		$this->commentsManager->deleteCommentsAtObject('announcement', (string) $id);
144
145 5
		$query = $this->connection->getQueryBuilder();
146 5
		$query->delete('announcements')
147 5
			->where($query->expr()->eq('announcement_id', $query->createNamedParameter((int) $id)));
148 5
		$query->execute();
149
150 5
		$query = $this->connection->getQueryBuilder();
151 5
		$query->delete('announcements_groups')
152 5
			->where($query->expr()->eq('announcement_id', $query->createNamedParameter((int) $id)));
153 5
		$query->execute();
154 5
	}
155
156
	/**
157
	 * @param int $id
158
	 * @param bool $parseStrings
159
	 * @param bool $ignorePermissions
160
	 * @param bool $returnGroups
161
	 * @return array
162
	 * @throws \InvalidArgumentException when the id is invalid
163
	 */
164 6
	public function getAnnouncement(int $id, bool $parseStrings = true, bool $ignorePermissions = false, bool $returnGroups = true): array {
165 6
		if (!$ignorePermissions) {
166 4
			$user = $this->userSession->getUser();
167 4 View Code Duplication
			if ($user instanceof IUser) {
0 ignored issues
show
Bug introduced by
The class OCP\IUser does not exist. Did you forget a USE statement, or did you not list all dependencies?

This error could be the result of:

1. Missing dependencies

PHP Analyzer uses your composer.json file (if available) to determine the dependencies of your project and to determine all the available classes and functions. It expects the composer.json to be in the root folder of your repository.

Are you sure this class is defined by one of your dependencies, or did you maybe not list a dependency in either the require or require-dev section?

2. Missing use statement

PHP does not complain about undefined classes in ìnstanceof checks. For example, the following PHP code will work perfectly fine:

if ($x instanceof DoesNotExist) {
    // Do something.
}

If you have not tested against this specific condition, such errors might go unnoticed.

Loading history...
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
168 2
				$userGroups = $this->groupManager->getUserGroupIds($user);
169 2
				$userGroups[] = 'everyone';
170
			} else {
171 2
				$userGroups = ['everyone'];
172
			}
173 4
			$isInAdminGroups = array_intersect($this->getAdminGroups(), $userGroups);
174
175 4
			if (empty($isInAdminGroups)) {
176 3
				$query = $this->connection->getQueryBuilder();
177 3
				$query->select('*')
178 3
					->from('announcements_groups')
179 3
					->where($query->expr()->eq('announcement_id', $query->createNamedParameter((int) $id)))
180 3
					->andWhere($query->expr()->in('gid', $query->createNamedParameter($userGroups, IQueryBuilder::PARAM_STR_ARRAY)))
181 3
					->setMaxResults(1);
182 3
				$result = $query->execute();
183 3
				$entry = $result->fetch();
184 3
				$result->closeCursor();
185
186 3
				if (!$entry) {
187 3
					throw new \InvalidArgumentException('Invalid ID');
188
				}
189
			}
190
		}
191
192 5
		$queryBuilder = $this->connection->getQueryBuilder();
193 5
		$query = $queryBuilder->select('*')
194 5
			->from('announcements')
195 5
			->where($queryBuilder->expr()->eq('announcement_id', $queryBuilder->createParameter('id')))
196 5
			->setParameter('id', (int) $id);
197 5
		$result = $query->execute();
198 5
		$row = $result->fetch();
199 5
		$result->closeCursor();
200
201 5
		if ($row === false) {
202 3
			throw new \InvalidArgumentException('Invalid ID');
203
		}
204
205 5
		$groups = null;
206 5
		if ($returnGroups && ($ignorePermissions || !empty($isInAdminGroups))) {
207 5
			$groups = $this->getGroups((int) $id);
208
		}
209
210
		$announcement = [
211 5
			'id'		=> (int) $row['announcement_id'],
212 5
			'author'	=> $row['announcement_user'],
213 5
			'time'		=> (int) $row['announcement_time'],
214 5
			'subject'	=> $parseStrings ? $this->parseSubject($row['announcement_subject']) : $row['announcement_subject'],
215 5
			'message'	=> $row['announcement_message'],
216 5
			'groups'	=> $groups,
217 5
			'comments'	=> $row['allow_comments'] ? 0 : false,
218
		];
219
220 5
		if ($ignorePermissions || !empty($isInAdminGroups)) {
221 5
			$announcement['notifications'] = $this->hasNotifications((int) $id);
222
		}
223
224 5
		return $announcement;
225
	}
226
227 3
	public function getAnnouncements(int $limit = 15, int $offset = 0, bool $parseStrings = true): array {
228 3
		$query = $this->connection->getQueryBuilder();
229 3
		$query->select('a.announcement_id')
230 3
			->from('announcements', 'a')
231 3
			->orderBy('a.announcement_time', 'DESC')
232 3
			->groupBy('a.announcement_id')
233 3
			->setMaxResults($limit);
234
235 3
		$user = $this->userSession->getUser();
236 3 View Code Duplication
		if ($user instanceof IUser) {
0 ignored issues
show
Bug introduced by
The class OCP\IUser does not exist. Did you forget a USE statement, or did you not list all dependencies?

This error could be the result of:

1. Missing dependencies

PHP Analyzer uses your composer.json file (if available) to determine the dependencies of your project and to determine all the available classes and functions. It expects the composer.json to be in the root folder of your repository.

Are you sure this class is defined by one of your dependencies, or did you maybe not list a dependency in either the require or require-dev section?

2. Missing use statement

PHP does not complain about undefined classes in ìnstanceof checks. For example, the following PHP code will work perfectly fine:

if ($x instanceof DoesNotExist) {
    // Do something.
}

If you have not tested against this specific condition, such errors might go unnoticed.

Loading history...
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
237 2
			$userGroups = $this->groupManager->getUserGroupIds($user);
238 2
			$userGroups[] = 'everyone';
239
		} else {
240 1
			$userGroups = ['everyone'];
241
		}
242
243 3
		$isInAdminGroups = array_intersect($this->getAdminGroups(), $userGroups);
244 3
		if (empty($isInAdminGroups)) {
245 2
			$query->leftJoin('a', 'announcements_groups', 'ag', $query->expr()->eq(
246 2
					'a.announcement_id', 'ag.announcement_id'
247
				))
248 2
				->andWhere($query->expr()->in('ag.gid', $query->createNamedParameter($userGroups, IQueryBuilder::PARAM_STR_ARRAY)));
249
		}
250
251 3
		if ($offset > 0) {
252 3
			$query->andWhere($query->expr()->lt('a.announcement_id', $query->createNamedParameter($offset, IQueryBuilder::PARAM_INT)));
253
		}
254
255 3
		$ids = [];
256 3
		$result = $query->execute();
257 3
		while ($row = $result->fetch()) {
258 3
			$ids[] = (int) $row['announcement_id'];
259
		}
260 3
		$result->closeCursor();
261
262 3
		if (empty($ids)) {
263 3
			return [];
264
		}
265
266 3
		$query = $this->connection->getQueryBuilder();
267 3
		$query->select('*')
268 3
			->from('announcements')
269 3
			->orderBy('announcement_time', 'DESC')
270 3
			->where($query->expr()->in('announcement_id', $query->createNamedParameter($ids, IQueryBuilder::PARAM_INT_ARRAY)));
271 3
		$result = $query->execute();
272
273 3
		$announcements = [];
274 3
		while ($row = $result->fetch()) {
275 3
			$id = (int) $row['announcement_id'];
276 3
			$announcements[$id] = [
277 3
				'id'		=> $id,
278 3
				'author'	=> $row['announcement_user'],
279 3
				'time'		=> (int) $row['announcement_time'],
280 3
				'subject'	=> $parseStrings ? $this->parseSubject($row['announcement_subject']) : $row['announcement_subject'],
281 3
				'message'	=> $row['announcement_message'],
282
				'groups'	=> null,
283 3
				'comments'	=> $row['allow_comments'] ? $this->getNumberOfComments($id) : false,
284
			];
285
286 3
			if (!empty($isInAdminGroups)) {
287 1
				$announcements[$id]['notifications'] = $this->hasNotifications($id);
288
			}
289
		}
290 3
		$result->closeCursor();
291
292 3
		if (!empty($isInAdminGroups)) {
293 1
			$allGroups = $this->getGroups(array_keys($announcements));
294 1
			foreach ($allGroups as $id => $groups) {
295 1
				$announcements[$id]['groups'] = $groups;
296
			}
297
		}
298
299 3
		return $announcements;
300
	}
301
302
	/**
303
	 * Return the groups (or string everyone) which have access to the announcement(s)
304
	 *
305
	 * @param int|int[] $ids
306
	 * @return string[]|array[]
307
	 */
308 5
	public function getGroups($ids): array {
309 5
		$returnSingleResult = false;
310 5
		if (\is_int($ids)) {
311 5
			$ids = [$ids];
312 5
			$returnSingleResult = true;
313
		}
314
315 5
		$query = $this->connection->getQueryBuilder();
316 5
		$query->select('*')
317 5
			->from('announcements_groups')
318 5
			->where($query->expr()->in('announcement_id', $query->createNamedParameter($ids, IQueryBuilder::PARAM_INT_ARRAY)));
319 5
		$result = $query->execute();
320
321 5
		$groups = [];
322 5
		while ($row = $result->fetch()) {
323 5
			if (!isset($groups[(int) $row['announcement_id']])) {
324 5
				$groups[(int) $row['announcement_id']] = [];
325
			}
326 5
			$groups[(int) $row['announcement_id']][] = $row['gid'];
327
		}
328 5
		$result->closeCursor();
329
330 5
		return $returnSingleResult ? (array) array_pop($groups) : $groups;
331
	}
332
333
	public function markNotificationRead(int $id) {
334
		$user = $this->userSession->getUser();
335
336
		if ($user instanceof IUser) {
0 ignored issues
show
Bug introduced by
The class OCP\IUser does not exist. Did you forget a USE statement, or did you not list all dependencies?

This error could be the result of:

1. Missing dependencies

PHP Analyzer uses your composer.json file (if available) to determine the dependencies of your project and to determine all the available classes and functions. It expects the composer.json to be in the root folder of your repository.

Are you sure this class is defined by one of your dependencies, or did you maybe not list a dependency in either the require or require-dev section?

2. Missing use statement

PHP does not complain about undefined classes in ìnstanceof checks. For example, the following PHP code will work perfectly fine:

if ($x instanceof DoesNotExist) {
    // Do something.
}

If you have not tested against this specific condition, such errors might go unnoticed.

Loading history...
337
			$notification = $this->notificationManager->createNotification();
338
			$notification->setApp('announcementcenter')
339
				->setUser($user->getUID())
340
				->setObject('announcement', $id);
341
			$this->notificationManager->markProcessed($notification);
342
		}
343
	}
344
345 2
	protected function getNumberOfComments(int $id): int {
346 2
		return $this->commentsManager->getNumberOfCommentsForObject('announcement', (string) $id);
347
	}
348
349 5
	protected function hasNotifications(int $id): bool {
350 5
		$hasJob = $this->jobList->has(BackgroundJob::class, [
351 5
			'id' => $id,
352
			'activities' => true,
353
			'notifications' => true,
354
		]);
355
356 5
		$hasJob = $hasJob || $this->jobList->has(BackgroundJob::class, [
357 5
			'id' => $id,
358
			'activities' => false,
359
			'notifications' => true,
360
		]);
361
362 5
		if ($hasJob) {
363
			return true;
364
		}
365
366 5
		$notification = $this->notificationManager->createNotification();
367 5
		$notification->setApp('announcementcenter')
368 5
			->setObject('announcement', $id);
369 5
		return $this->notificationManager->getCount($notification) > 0;
370
	}
371
372
	public function removeNotifications(int $id) {
373
		if ($this->jobList->has(BackgroundJob::class, [
374
			'id' => $id,
375
			'activities' => true,
376
			'notifications' => true,
377
		])) {
378
			// Delete the current background job and add a new one without notifications
379
			$this->jobList->remove(BackgroundJob::class, [
380
				'id' => $id,
381
				'activities' => true,
382
				'notifications' => true,
383
			]);
384
			$this->jobList->add(BackgroundJob::class, [
385
				'id' => $id,
386
				'activities' => true,
387
				'notifications' => false,
388
			]);
389
390
		} else {
391
			$this->jobList->remove(BackgroundJob::class, [
392
				'id' => $id,
393
				'activities' => false,
394
				'notifications' => true,
395
			]);
396
		}
397
398
		$notification = $this->notificationManager->createNotification();
399
		$notification->setApp('announcementcenter')
400
			->setObject('announcement', $id);
401
		$this->notificationManager->markProcessed($notification);
402
	}
403
404
	protected function parseMessage(string $message): string {
405
		return str_replace(['<', '>', "\n"], ['&lt;', '&gt;', '<br />'], $message);
406
	}
407
408 5
	protected function parseSubject(string $subject): string {
409 5
		return str_replace(['<', '>', "\n"], ['&lt;', '&gt;', ' '], $subject);
410
	}
411
412
	/**
413
	 * Check if the user is in the admin group
414
	 */
415 6
	public function checkIsAdmin(): bool {
416 6
		$user = $this->userSession->getUser();
417
418 6
		if ($user instanceof IUser) {
0 ignored issues
show
Bug introduced by
The class OCP\IUser does not exist. Did you forget a USE statement, or did you not list all dependencies?

This error could be the result of:

1. Missing dependencies

PHP Analyzer uses your composer.json file (if available) to determine the dependencies of your project and to determine all the available classes and functions. It expects the composer.json to be in the root folder of your repository.

Are you sure this class is defined by one of your dependencies, or did you maybe not list a dependency in either the require or require-dev section?

2. Missing use statement

PHP does not complain about undefined classes in ìnstanceof checks. For example, the following PHP code will work perfectly fine:

if ($x instanceof DoesNotExist) {
    // Do something.
}

If you have not tested against this specific condition, such errors might go unnoticed.

Loading history...
419 5
			$groups = $this->getAdminGroups();
420 5
			foreach ($groups as $group) {
421 5
				if ($this->groupManager->isInGroup($user->getUID(), $group)) {
422 5
					return true;
423
				}
424
			}
425
		}
426
427 3
		return false;
428
	}
429
430
	/**
431
	 * @return string[]
432
	 */
433 9
	protected function getAdminGroups(): array {
434 9
		$adminGroups = $this->config->getAppValue('announcementcenter', 'admin_groups', '["admin"]');
435 9
		$adminGroups = json_decode($adminGroups, true);
436 9
		return $adminGroups;
437
	}
438
}
439