Completed
Push — master ( a2e3fa...56d3db )
by Joas
10s
created

Manager   B

Complexity

Total Complexity 46

Size/Duplication

Total Lines 350
Duplicated Lines 3.43 %

Coupling/Cohesion

Components 1
Dependencies 0

Test Coverage

Coverage 95%

Importance

Changes 0
Metric Value
wmc 46
lcom 1
cbo 0
dl 12
loc 350
ccs 190
cts 200
cp 0.95
rs 8.3999
c 0
b 0
f 0

13 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 13 1
B announce() 0 38 6
A addGroupLink() 0 9 1
A delete() 0 20 1
C getAnnouncement() 6 56 12
C getAnnouncements() 6 54 10
B getGroups() 0 24 5
A markNotificationRead() 0 11 2
A getNumberOfComments() 0 3 1
A parseMessage() 0 3 1
A parseSubject() 0 3 1
A checkIsAdmin() 0 14 4
A getAdminGroups() 0 5 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
/**
3
 * @copyright Copyright (c) 2016, Joas Schilling <[email protected]>
4
 *
5
 * @author Joas Schilling <[email protected]>
6
 *
7
 * @license GNU AGPL version 3 or any later version
8
 *
9
 * This program is free software: you can redistribute it and/or modify
10
 * it under the terms of the GNU Affero General Public License as
11
 * published by the Free Software Foundation, either version 3 of the
12
 * License, or (at your option) any later version.
13
 *
14
 * This program is distributed in the hope that it will be useful,
15
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
16
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17
 * GNU Affero General Public License for more details.
18
 *
19
 * You should have received a copy of the GNU Affero General Public License
20
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
21
 *
22
 */
23
24
namespace OCA\AnnouncementCenter;
25
26
use OCP\Comments\ICommentsManager;
27
use OCP\DB\QueryBuilder\IQueryBuilder;
28
use OCP\IConfig;
29
use OCP\IDBConnection;
30
use OCP\IGroupManager;
31
use OCP\Notification\IManager as INotificationManager;
32
use OCP\IUser;
33
use OCP\IUserSession;
34
35
class Manager {
36
37
	/** @var IConfig */
38
	protected $config;
39
40
	/** @var IDBConnection */
41
	protected $connection;
42
43
	/** @var IGroupManager */
44
	protected $groupManager;
45
46
	/** @var INotificationManager */
47
	protected $notificationManager;
48
49
	/** @var ICommentsManager */
50
	protected $commentsManager;
51
52
	/** @var IUserSession */
53
	protected $userSession;
54
55
	/**
56
	 * @param IConfig $config
57
	 * @param IDBConnection $connection
58
	 * @param IGroupManager $groupManager
59
	 * @param INotificationManager $notificationManager
60
	 * @param ICommentsManager $commentsManager
61
	 * @param IUserSession $userSession
62
	 */
63 21
	public function __construct(IConfig $config,
64
								IDBConnection $connection,
65
								IGroupManager $groupManager,
66
								INotificationManager $notificationManager,
67
								ICommentsManager $commentsManager,
68
								IUserSession $userSession) {
69 21
		$this->config = $config;
70 21
		$this->connection = $connection;
71 21
		$this->groupManager = $groupManager;
72 21
		$this->notificationManager = $notificationManager;
73 21
		$this->commentsManager = $commentsManager;
74 21
		$this->userSession = $userSession;
75 21
	}
76
77
	/**
78
	 * @param string $subject
79
	 * @param string $message
80
	 * @param string $user
81
	 * @param int $time
82
	 * @param string[] $groups
83
	 * @param bool $comments
84
	 * @return array
85
	 * @throws \InvalidArgumentException when the subject is empty or invalid
86
	 */
87 7
	public function announce($subject, $message, $user, $time, array $groups, $comments) {
88 7
		$subject = trim($subject);
89 7
		$message = trim($message);
90 7
		if (isset($subject[512])) {
91 1
			throw new \InvalidArgumentException('Invalid subject', 1);
92
		}
93
94 6
		if ($subject === '') {
95 1
			throw new \InvalidArgumentException('Invalid subject', 2);
96
		}
97
98 5
		$queryBuilder = $this->connection->getQueryBuilder();
99 5
		$queryBuilder->insert('announcements')
100 5
			->values([
101 5
				'announcement_time' => $queryBuilder->createNamedParameter($time),
102 5
				'announcement_user' => $queryBuilder->createNamedParameter($user),
103 5
				'announcement_subject' => $queryBuilder->createNamedParameter($subject),
104 5
				'announcement_message' => $queryBuilder->createNamedParameter($message),
105 5
				'allow_comments' => $queryBuilder->createNamedParameter((int) $comments),
106 5
			]);
107 5
		$queryBuilder->execute();
108
109 5
		$id = $queryBuilder->getLastInsertId();
110
111 5
		$addedGroups = 0;
112 5
		foreach ($groups as $group) {
113 5
			if ($this->groupManager->groupExists($group)) {
114 4
				$this->addGroupLink((int) $id, $group);
115 4
				$addedGroups++;
116 4
			}
117 5
		}
118
119 5
		if ($addedGroups === 0) {
120 4
			$this->addGroupLink((int) $id, 'everyone');
121 4
		}
122
123 5
		return $this->getAnnouncement($id, true, true);
124
	}
125
126
	/**
127
	 * @param int $announcementId
128
	 * @param string $group
129
	 */
130 5
	protected function addGroupLink($announcementId, $group) {
131 5
		$query = $this->connection->getQueryBuilder();
132 5
		$query->insert('announcements_groups')
133 5
			->values([
134 5
				'announcement_id' => $query->createNamedParameter($announcementId),
135 5
				'gid' => $query->createNamedParameter($group),
136 5
			]);
137 5
		$query->execute();
138 5
	}
139
140
	/**
141
	 * @param int $id
142
	 */
143 5
	public function delete($id) {
144
		// Delete notifications
145 5
		$notification = $this->notificationManager->createNotification();
146 5
		$notification->setApp('announcementcenter')
147 5
			->setObject('announcement', $id);
148 5
		$this->notificationManager->markProcessed($notification);
149
150
		// Delete comments
151 5
		$this->commentsManager->deleteCommentsAtObject('announcement', (string) $id);
152
153 5
		$query = $this->connection->getQueryBuilder();
154 5
		$query->delete('announcements')
155 5
			->where($query->expr()->eq('announcement_id', $query->createNamedParameter((int) $id)));
156 5
		$query->execute();
157
158 5
		$query = $this->connection->getQueryBuilder();
159 5
		$query->delete('announcements_groups')
160 5
			->where($query->expr()->eq('announcement_id', $query->createNamedParameter((int) $id)));
161 5
		$query->execute();
162 5
	}
163
164
	/**
165
	 * @param int $id
166
	 * @param bool $parseStrings
167
	 * @param bool $ignorePermissions
168
	 * @param bool $returnGroups
169
	 * @return array
170
	 * @throws \InvalidArgumentException when the id is invalid
171
	 */
172 6
	public function getAnnouncement($id, $parseStrings = true, $ignorePermissions = false, $returnGroups = true) {
173 6
		if (!$ignorePermissions) {
174 4
			$user = $this->userSession->getUser();
175 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...
176 2
				$userGroups = $this->groupManager->getUserGroupIds($user);
177 2
				$userGroups[] = 'everyone';
178 2
			} else {
179 2
				$userGroups = ['everyone'];
180
			}
181 4
			$isInAdminGroups = array_intersect($this->getAdminGroups(), $userGroups);
182
183 4
			if (empty($isInAdminGroups)) {
184 3
				$query = $this->connection->getQueryBuilder();
185 3
				$query->select('*')
186 3
					->from('announcements_groups')
187 3
					->where($query->expr()->eq('announcement_id', $query->createNamedParameter((int) $id)))
188 3
					->andWhere($query->expr()->in('gid', $query->createNamedParameter($userGroups, IQueryBuilder::PARAM_STR_ARRAY)))
189 3
					->setMaxResults(1);
190 3
				$result = $query->execute();
191 3
				$entry = $result->fetch();
192 3
				$result->closeCursor();
193
194 3
				if (!$entry) {
195 3
					throw new \InvalidArgumentException('Invalid ID');
196
				}
197 2
			}
198 3
		}
199
200 5
		$queryBuilder = $this->connection->getQueryBuilder();
201 5
		$query = $queryBuilder->select('*')
202 5
			->from('announcements')
203 5
			->where($queryBuilder->expr()->eq('announcement_id', $queryBuilder->createParameter('id')))
204 5
			->setParameter('id', (int) $id);
205 5
		$result = $query->execute();
206 5
		$row = $result->fetch();
207 5
		$result->closeCursor();
208
209 5
		if ($row === false) {
210 3
			throw new \InvalidArgumentException('Invalid ID');
211
		}
212
213 5
		$groups = null;
214 5
		if ($returnGroups && ($ignorePermissions || !empty($isInAdminGroups))) {
215 5
			$groups = $this->getGroups((int) $id);
216 5
		}
217
218
		return [
219 5
			'id'		=> (int) $row['announcement_id'],
220 5
			'author'	=> $row['announcement_user'],
221 5
			'time'		=> (int) $row['announcement_time'],
222 5
			'subject'	=> ($parseStrings) ? $this->parseSubject($row['announcement_subject']) : $row['announcement_subject'],
223 5
			'message'	=> ($parseStrings) ? $this->parseMessage($row['announcement_message']) : $row['announcement_message'],
224 5
			'groups'	=> $groups,
225 5
			'comments'	=> $row['allow_comments'] ? 0 : false,
226 5
		];
227
	}
228
229
	/**
230
	 * @param int $limit
231
	 * @param int $offset
232
	 * @param bool $parseStrings
233
	 * @return array
234
	 */
235 3
	public function getAnnouncements($limit = 15, $offset = 0, $parseStrings = true) {
236 3
		$query = $this->connection->getQueryBuilder();
237 3
		$query->select('a.*')
238 3
			->from('announcements', 'a')
239 3
			->orderBy('a.announcement_time', 'DESC')
240 3
			->groupBy('a.announcement_id')
241 3
			->setMaxResults($limit);
242
243 3
		$user = $this->userSession->getUser();
244 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...
245 2
			$userGroups = $this->groupManager->getUserGroupIds($user);
246 2
			$userGroups[] = 'everyone';
247 2
		} else {
248 1
			$userGroups = ['everyone'];
249
		}
250
251 3
		$isInAdminGroups = array_intersect($this->getAdminGroups(), $userGroups);
252 3
		if (empty($isInAdminGroups)) {
253 2
			$query->leftJoin('a', 'announcements_groups', 'ag', $query->expr()->eq(
254 2
					'a.announcement_id', 'ag.announcement_id'
255 2
				))
256 2
				->andWhere($query->expr()->in('ag.gid', $query->createNamedParameter($userGroups, IQueryBuilder::PARAM_STR_ARRAY)));
257 2
		}
258
259 3
		if ($offset > 0) {
260 3
			$query->andWhere($query->expr()->lt('a.announcement_id', $query->createNamedParameter($offset, IQueryBuilder::PARAM_INT)));
261 3
		}
262
263 3
		$result = $query->execute();
264
265 3
		$announcements = [];
266 3
		while ($row = $result->fetch()) {
267 3
			$id = (int) $row['announcement_id'];
268 3
			$announcements[$id] = [
269 3
				'id'		=> $id,
270 3
				'author'	=> $row['announcement_user'],
271 3
				'time'		=> (int) $row['announcement_time'],
272 3
				'subject'	=> ($parseStrings) ? $this->parseSubject($row['announcement_subject']) : $row['announcement_subject'],
273 3
				'message'	=> ($parseStrings) ? $this->parseMessage($row['announcement_message']) : $row['announcement_message'],
274 3
				'groups'	=> null,
275 3
				'comments'	=> $row['allow_comments'] ? $this->getNumberOfComments($id) : false,
276
			];
277 3
		}
278 3
		$result->closeCursor();
279
280 3
		if (!empty($isInAdminGroups)) {
281 1
			$allGroups = $this->getGroups(array_keys($announcements));
282 1
			foreach ($allGroups as $id => $groups) {
283 1
				$announcements[$id]['groups'] = $groups;
284 1
			}
285 1
		}
286
287 3
		return $announcements;
288
	}
289
290
	/**
291
	 * Return the groups (or string everyone) which have access to the announcement(s)
292
	 *
293
	 * @param int|int[] $ids
294
	 * @return string[]|array[]
295
	 */
296 5
	public function getGroups($ids) {
297 5
		$returnSingleResult = false;
298 5
		if (is_int($ids)) {
299 5
			$ids = [$ids];
300 5
			$returnSingleResult = true;
301 5
		}
302
303 5
		$query = $this->connection->getQueryBuilder();
304 5
		$query->select('*')
305 5
			->from('announcements_groups')
306 5
			->where($query->expr()->in('announcement_id', $query->createNamedParameter($ids, IQueryBuilder::PARAM_INT_ARRAY)));
307 5
		$result = $query->execute();
308
309 5
		$groups = [];
310 5
		while ($row = $result->fetch()) {
311 5
			if (!isset($groups[(int) $row['announcement_id']])) {
312 5
				$groups[(int) $row['announcement_id']] = [];
313 5
			}
314 5
			$groups[(int) $row['announcement_id']][] = $row['gid'];
315 5
		}
316 5
		$result->closeCursor();
317
318 5
		return $returnSingleResult ? (array) array_pop($groups) : $groups;
319
	}
320
321
	/**
322
	 * @param int $id
323
	 */
324
	public function markNotificationRead($id) {
325
		$user = $this->userSession->getUser();
326
327
		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...
328
			$notification = $this->notificationManager->createNotification();
329
			$notification->setApp('announcementcenter')
330
				->setUser($user->getUID())
331
				->setObject('announcement', $id);
332
			$this->notificationManager->markProcessed($notification);
333
		}
334
	}
335
336
	/**
337
	 * @param int $id
338
	 * @return int
339
	 */
340 2
	protected function getNumberOfComments($id) {
341 2
		return $this->commentsManager->getNumberOfCommentsForObject('announcement', (string) $id);
342
	}
343
344
	/**
345
	 * @param string $message
346
	 * @return string
347
	 */
348 5
	protected function parseMessage($message) {
349 5
		return str_replace("\n", '<br />', str_replace(['<', '>'], ['&lt;', '&gt;'], $message));
350
	}
351
352
	/**
353
	 * @param string $subject
354
	 * @return string
355
	 */
356 5
	protected function parseSubject($subject) {
357 5
		return str_replace("\n", ' ', str_replace(['<', '>'], ['&lt;', '&gt;'], $subject));
358
	}
359
360
	/**
361
	 * Check if the user is in the admin group
362
	 * @return bool
363
	 */
364 6
	public function checkIsAdmin() {
365 6
		$user = $this->userSession->getUser();
366
367 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...
368 5
			$groups = $this->getAdminGroups();
369 5
			foreach ($groups as $group) {
370 5
				if ($this->groupManager->isInGroup($user->getUID(), $group)) {
371 3
					return true;
372
				}
373 3
			}
374 2
		}
375
376 3
		return false;
377
	}
378
379 9
	protected function getAdminGroups() {
380 9
		$adminGroups = $this->config->getAppValue('announcementcenter', 'admin_groups', '["admin"]');
381 9
		$adminGroups = json_decode($adminGroups, true);
382 9
		return $adminGroups;
383
	}
384
}
385