Completed
Pull Request — master (#20)
by Joas
04:39
created

Manager::getAnnouncement()   C

Complexity

Conditions 12
Paths 87

Size

Total Lines 56
Code Lines 42

Duplication

Lines 6
Ratio 10.71 %

Code Coverage

Tests 45
CRAP Score 12

Importance

Changes 11
Bugs 2 Features 2
Metric Value
c 11
b 2
f 2
dl 6
loc 56
ccs 45
cts 45
cp 1
rs 6.7092
cc 12
eloc 42
nc 87
nop 3
crap 12

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
/**
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 17
	public function __construct(IConfig $config,
64
								IDBConnection $connection,
65
								IGroupManager $groupManager,
66
								INotificationManager $notificationManager,
67
								ICommentsManager $commentsManager,
68
								IUserSession $userSession) {
69 17
		$this->config = $config;
70 17
		$this->connection = $connection;
71 17
		$this->groupManager = $groupManager;
72 17
		$this->notificationManager = $notificationManager;
73 17
		$this->commentsManager = $commentsManager;
74 17
		$this->userSession = $userSession;
75 17
	}
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
	 * @return array
169
	 * @throws \InvalidArgumentException when the id is invalid
170
	 */
171 6
	public function getAnnouncement($id, $parseStrings = true, $ignorePermissions = false) {
172 6
		if (!$ignorePermissions) {
173 4
			$user = $this->userSession->getUser();
174 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...
175 2
				$userGroups = $this->groupManager->getUserGroupIds($user);
176 2
				$userGroups[] = 'everyone';
177 2
			} else {
178 2
				$userGroups = ['everyone'];
179
			}
180 4
			$isInAdminGroups = array_intersect($this->getAdminGroups(), $userGroups);
181
182 4
			if (empty($isInAdminGroups)) {
183 3
				$query = $this->connection->getQueryBuilder();
184 3
				$query->select('*')
185 3
					->from('announcements_groups')
186 3
					->where($query->expr()->eq('announcement_id', $query->createNamedParameter((int) $id)))
187 3
					->andWhere($query->expr()->in('gid', $query->createNamedParameter($userGroups, IQueryBuilder::PARAM_STR_ARRAY)))
188 3
					->setMaxResults(1);
189 3
				$result = $query->execute();
190 3
				$entry = $result->fetch();
191 3
				$result->closeCursor();
192
193 3
				if (!$entry) {
194 3
					throw new \InvalidArgumentException('Invalid ID');
195
				}
196 2
			}
197 3
		}
198
199 5
		$queryBuilder = $this->connection->getQueryBuilder();
200 5
		$query = $queryBuilder->select('*')
201 5
			->from('announcements')
202 5
			->where($queryBuilder->expr()->eq('announcement_id', $queryBuilder->createParameter('id')))
203 5
			->setParameter('id', (int) $id);
204 5
		$result = $query->execute();
205 5
		$row = $result->fetch();
206 5
		$result->closeCursor();
207
208 5
		if ($row === false) {
209 3
			throw new \InvalidArgumentException('Invalid ID');
210
		}
211
212 5
		$groups = null;
213 5
		if ($ignorePermissions || (isset($isInAdminGroups) && !empty($isInAdminGroups))) {
214 5
			$groups = $this->getGroups($id);
215 5
		}
216
217
		return [
218 5
			'id'		=> (int) $row['announcement_id'],
219 5
			'author'	=> $row['announcement_user'],
220 5
			'time'		=> (int) $row['announcement_time'],
221 5
			'subject'	=> ($parseStrings) ? $this->parseSubject($row['announcement_subject']) : $row['announcement_subject'],
222 5
			'message'	=> ($parseStrings) ? $this->parseMessage($row['announcement_message']) : $row['announcement_message'],
223 5
			'groups'	=> $groups,
224 5
			'comments'	=> $row['allow_comments'] ? 0 : false,
225 5
		];
226
	}
227
228
	/**
229
	 * @param int $limit
230
	 * @param int $offset
231
	 * @param bool $parseStrings
232
	 * @return array
233
	 */
234 3
	public function getAnnouncements($limit = 15, $offset = 0, $parseStrings = true) {
235 3
		$query = $this->connection->getQueryBuilder();
236 3
		$query->select('a.*')
237 3
			->from('announcements', 'a')
238 3
			->orderBy('a.announcement_time', 'DESC')
239 3
			->groupBy('a.announcement_id')
240 3
			->setMaxResults($limit);
241
242 3
		$user = $this->userSession->getUser();
243 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...
244 2
			$userGroups = $this->groupManager->getUserGroupIds($user);
245 2
			$userGroups[] = 'everyone';
246 2
		} else {
247 1
			$userGroups = ['everyone'];
248
		}
249
250 3
		$isInAdminGroups = array_intersect($this->getAdminGroups(), $userGroups);
251 3
		if (empty($isInAdminGroups)) {
252 2
			$query->leftJoin('a', 'announcements_groups', 'ag', $query->expr()->eq(
253 2
					'a.announcement_id', 'ag.announcement_id'
254 2
				))
255 2
				->andWhere($query->expr()->in('ag.gid', $query->createNamedParameter($userGroups, IQueryBuilder::PARAM_STR_ARRAY)));
256 2
		}
257
258 3
		if ($offset > 0) {
259 3
			$query->andWhere($query->expr()->lt('a.announcement_id', $query->createNamedParameter($offset, IQueryBuilder::PARAM_INT)));
260 3
		}
261
262 3
		$result = $query->execute();
263
264 3
		$announcements = [];
265 3
		while ($row = $result->fetch()) {
266 3
			$id = (int) $row['announcement_id'];
267 3
			$announcements[$id] = [
268 3
				'id'		=> $id,
269 3
				'author'	=> $row['announcement_user'],
270 3
				'time'		=> (int) $row['announcement_time'],
271 3
				'subject'	=> ($parseStrings) ? $this->parseSubject($row['announcement_subject']) : $row['announcement_subject'],
272 3
				'message'	=> ($parseStrings) ? $this->parseMessage($row['announcement_message']) : $row['announcement_message'],
273 3
				'groups'	=> null,
274 3
				'comments'	=> $row['allow_comments'] ? $this->getNumberOfComments($id) : false,
275
			];
276 3
		}
277 3
		$result->closeCursor();
278
279 3
		if (!empty($isInAdminGroups)) {
280 1
			$allGroups = $this->getGroups(array_keys($announcements));
281 1
			foreach ($allGroups as $id => $groups) {
282 1
				$announcements[$id]['groups'] = $groups;
283 1
			}
284 1
		}
285
286 3
		return $announcements;
287
	}
288
289
	/**
290
	 * Return the groups (or string everyone) which have access to the announcement(s)
291
	 *
292
	 * @param int|int[] $ids
293
	 * @return string[]|array[]
294
	 */
295 5
	public function getGroups($ids) {
296 5
		$returnSingleResult = false;
297 5
		if (is_int($ids)) {
298 5
			$ids = [$ids];
299 5
			$returnSingleResult = true;
300 5
		}
301
302 5
		$query = $this->connection->getQueryBuilder();
303 5
		$query->select('*')
304 5
			->from('announcements_groups')
305 5
			->where($query->expr()->in('announcement_id', $query->createNamedParameter($ids, IQueryBuilder::PARAM_INT_ARRAY)));
306 5
		$result = $query->execute();
307
308 5
		$groups = [];
309 5
		while ($row = $result->fetch()) {
310 5
			if (!isset($groups[(int) $row['announcement_id']])) {
311 5
				$groups[(int) $row['announcement_id']] = [];
312 5
			}
313 5
			$groups[(int) $row['announcement_id']][] = $row['gid'];
314 5
		}
315 5
		$result->closeCursor();
316
317 5
		return $returnSingleResult ? (array) array_pop($groups) : $groups;
318
	}
319
320
	/**
321
	 * @param int $id
322
	 * @return int
323
	 */
324 2
	protected function getNumberOfComments($id) {
325 2
		return $this->commentsManager->getNumberOfCommentsForObject('announcement', (string) $id);
326
	}
327
328
	/**
329
	 * @param string $message
330
	 * @return string
331
	 */
332 5
	protected function parseMessage($message) {
333 5
		return str_replace("\n", '<br />', str_replace(['<', '>'], ['&lt;', '&gt;'], $message));
334
	}
335
336
	/**
337
	 * @param string $subject
338
	 * @return string
339
	 */
340 5
	protected function parseSubject($subject) {
341 5
		return str_replace("\n", ' ', str_replace(['<', '>'], ['&lt;', '&gt;'], $subject));
342
	}
343
344
	/**
345
	 * Check if the user is in the admin group
346
	 * @return bool
347
	 */
348 6
	public function checkIsAdmin() {
349 6
		$user = $this->userSession->getUser();
350
351 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...
352 5
			$groups = $this->getAdminGroups();
353 5
			foreach ($groups as $group) {
354 5
				if ($this->groupManager->isInGroup($user->getUID(), $group)) {
355 3
					return true;
356
				}
357 3
			}
358 2
		}
359
360 3
		return false;
361
	}
362
363 9
	protected function getAdminGroups() {
364 9
		$adminGroups = $this->config->getAppValue('announcementcenter', 'admin_groups', '["admin"]');
365 9
		$adminGroups = json_decode($adminGroups, true);
366 9
		return $adminGroups;
367
	}
368
}
369