Completed
Pull Request — master (#12)
by Joas
08:14
created

Manager::getAnnouncement()   C

Complexity

Conditions 11
Paths 47

Size

Total Lines 55
Code Lines 41

Duplication

Lines 6
Ratio 10.91 %

Code Coverage

Tests 44
CRAP Score 11

Importance

Changes 10
Bugs 2 Features 2
Metric Value
c 10
b 2
f 2
dl 6
loc 55
ccs 44
cts 44
cp 1
rs 6.6153
cc 11
eloc 41
nc 47
nop 3
crap 11

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 16
	public function __construct(IConfig $config,
64
								IDBConnection $connection,
65
								IGroupManager $groupManager,
66
								INotificationManager $notificationManager,
67
								ICommentsManager $commentsManager,
68
								IUserSession $userSession) {
69 16
		$this->config = $config;
70 16
		$this->connection = $connection;
71 16
		$this->groupManager = $groupManager;
72 16
		$this->notificationManager = $notificationManager;
73 16
		$this->commentsManager = $commentsManager;
74 16
		$this->userSession = $userSession;
75 16
	}
76
77
	/**
78
	 * @param string $subject
79
	 * @param string $message
80
	 * @param string $user
81
	 * @param int $time
82
	 * @param string[] $groups
83
	 * @return array
84
	 * @throws \InvalidArgumentException when the subject is empty or invalid
85
	 */
86 7
	public function announce($subject, $message, $user, $time, array $groups) {
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
			]);
105 5
		$queryBuilder->execute();
106
107 5
		$id = $queryBuilder->getLastInsertId();
108
109 5
		$addedGroups = 0;
110 5
		foreach ($groups as $group) {
111 5
			if ($this->groupManager->groupExists($group)) {
112 4
				$this->addGroupLink((int) $id, $group);
113 4
				$addedGroups++;
114 4
			}
115 5
		}
116
117 5
		if ($addedGroups === 0) {
118 4
			$this->addGroupLink((int) $id, 'everyone');
119 4
		}
120
121 5
		return $this->getAnnouncement($id, true, true);
122
	}
123
124
	/**
125
	 * @param int $announcementId
126
	 * @param string $group
127
	 */
128 5
	protected function addGroupLink($announcementId, $group) {
129 5
		$query = $this->connection->getQueryBuilder();
130 5
		$query->insert('announcements_groups')
131 5
			->values([
132 5
				'announcement_id' => $query->createNamedParameter($announcementId),
133 5
				'gid' => $query->createNamedParameter($group),
134 5
			]);
135 5
		$query->execute();
136 5
	}
137
138
	/**
139
	 * @param int $id
140
	 */
141 5
	public function delete($id) {
142
		// Delete notifications
143 5
		$notification = $this->notificationManager->createNotification();
144 5
		$notification->setApp('announcementcenter')
145 5
			->setObject('announcement', $id);
146 5
		$this->notificationManager->markProcessed($notification);
147
148
		// Delete comments
149 5
		$this->commentsManager->deleteCommentsAtObject('announcement', (string) $id);
150
151 5
		$query = $this->connection->getQueryBuilder();
152 5
		$query->delete('announcements')
153 5
			->where($query->expr()->eq('announcement_id', $query->createNamedParameter((int) $id)));
154 5
		$query->execute();
155
156 5
		$query = $this->connection->getQueryBuilder();
157 5
		$query->delete('announcements_groups')
158 5
			->where($query->expr()->eq('announcement_id', $query->createNamedParameter((int) $id)));
159 5
		$query->execute();
160 5
	}
161
162
	/**
163
	 * @param int $id
164
	 * @param bool $parseStrings
165
	 * @param bool $ignorePermissions
166
	 * @return array
167
	 * @throws \InvalidArgumentException when the id is invalid
168
	 */
169 6
	public function getAnnouncement($id, $parseStrings = true, $ignorePermissions = false) {
170 6
		if (!$ignorePermissions) {
171 4
			$user = $this->userSession->getUser();
172 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...
173 2
				$userGroups = $this->groupManager->getUserGroupIds($user);
174 2
				$userGroups[] = 'everyone';
175 2
			} else {
176 2
				$userGroups = ['everyone'];
177
			}
178 4
			$isInAdminGroups = array_intersect($this->getAdminGroups(), $userGroups);
179
180 4
			if (empty($isInAdminGroups)) {
181 3
				$query = $this->connection->getQueryBuilder();
182 3
				$query->select('*')
183 3
					->from('announcements_groups')
184 3
					->where($query->expr()->eq('announcement_id', $query->createNamedParameter((int) $id)))
185 3
					->andWhere($query->expr()->in('gid', $query->createNamedParameter($userGroups, IQueryBuilder::PARAM_STR_ARRAY)))
186 3
					->setMaxResults(1);
187 3
				$result = $query->execute();
188 3
				$entry = $result->fetch();
189 3
				$result->closeCursor();
190
191 3
				if (!$entry) {
192 3
					throw new \InvalidArgumentException('Invalid ID');
193
				}
194 2
			}
195 3
		}
196
197 5
		$queryBuilder = $this->connection->getQueryBuilder();
198 5
		$query = $queryBuilder->select('*')
199 5
			->from('announcements')
200 5
			->where($queryBuilder->expr()->eq('announcement_id', $queryBuilder->createParameter('id')))
201 5
			->setParameter('id', (int) $id);
202 5
		$result = $query->execute();
203 5
		$row = $result->fetch();
204 5
		$result->closeCursor();
205
206 5
		if ($row === false) {
207 3
			throw new \InvalidArgumentException('Invalid ID');
208
		}
209
210 5
		$groups = null;
211 5
		if ($ignorePermissions || (isset($isInAdminGroups) && !empty($isInAdminGroups))) {
212 5
			$groups = $this->getGroups($id);
213 5
		}
214
215
		return [
216 5
			'id'		=> (int) $row['announcement_id'],
217 5
			'author'	=> $row['announcement_user'],
218 5
			'time'		=> (int) $row['announcement_time'],
219 5
			'subject'	=> ($parseStrings) ? $this->parseSubject($row['announcement_subject']) : $row['announcement_subject'],
220 5
			'message'	=> ($parseStrings) ? $this->parseMessage($row['announcement_message']) : $row['announcement_message'],
221 5
			'groups'	=> $groups,
222 5
		];
223
	}
224
225
	/**
226
	 * @param int $limit
227
	 * @param int $offset
228
	 * @param bool $parseStrings
229
	 * @return array
230
	 */
231 3
	public function getAnnouncements($limit = 15, $offset = 0, $parseStrings = true) {
232 3
		$query = $this->connection->getQueryBuilder();
233 3
		$query->select('a.*')
234 3
			->from('announcements', 'a')
235 3
			->orderBy('a.announcement_time', 'DESC')
236 3
			->groupBy('a.announcement_id')
237 3
			->setMaxResults($limit);
238
239 3
		$user = $this->userSession->getUser();
240 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...
241 2
			$userGroups = $this->groupManager->getUserGroupIds($user);
242 2
			$userGroups[] = 'everyone';
243 2
		} else {
244 1
			$userGroups = ['everyone'];
245
		}
246
247 3
		$isInAdminGroups = array_intersect($this->getAdminGroups(), $userGroups);
248 3
		if (empty($isInAdminGroups)) {
249 2
			$query->leftJoin('a', 'announcements_groups', 'ag', $query->expr()->eq(
250 2
					'a.announcement_id', 'ag.announcement_id'
251 2
				))
252 2
				->andWhere($query->expr()->in('ag.gid', $query->createNamedParameter($userGroups, IQueryBuilder::PARAM_STR_ARRAY)));
253 2
		}
254
255 3
		if ($offset > 0) {
256 3
			$query->andWhere($query->expr()->lt('a.announcement_id', $query->createNamedParameter($offset, IQueryBuilder::PARAM_INT)));
257 3
		}
258
259 3
		$result = $query->execute();
260
261 3
		$announcements = [];
262 3
		while ($row = $result->fetch()) {
263 3
			$id = (int) $row['announcement_id'];
264 3
			$announcements[$id] = [
265 3
				'id'		=> $id,
266 3
				'author'	=> $row['announcement_user'],
267 3
				'time'		=> (int) $row['announcement_time'],
268 3
				'subject'	=> ($parseStrings) ? $this->parseSubject($row['announcement_subject']) : $row['announcement_subject'],
269 3
				'message'	=> ($parseStrings) ? $this->parseMessage($row['announcement_message']) : $row['announcement_message'],
270 3
				'groups'	=> null,
271
			];
272 3
		}
273 3
		$result->closeCursor();
274
275 3
		if (!empty($isInAdminGroups)) {
276 1
			$allGroups = $this->getGroups(array_keys($announcements));
277 1
			foreach ($allGroups as $id => $groups) {
278 1
				$announcements[$id]['groups'] = $groups;
279 1
			}
280 1
		}
281
282 3
		return $announcements;
283
	}
284
285
	/**
286
	 * Return the groups (or string everyone) which have access to the announcement(s)
287
	 *
288
	 * @param int|int[] $ids
289
	 * @return string[]|array[]
290
	 */
291 5
	public function getGroups($ids) {
292 5
		$returnSingleResult = false;
293 5
		if (is_int($ids)) {
294 5
			$ids = [$ids];
295 5
			$returnSingleResult = true;
296 5
		}
297
298 5
		$query = $this->connection->getQueryBuilder();
299 5
		$query->select('*')
300 5
			->from('announcements_groups')
301 5
			->where($query->expr()->in('announcement_id', $query->createNamedParameter($ids, IQueryBuilder::PARAM_INT_ARRAY)));
302 5
		$result = $query->execute();
303
304 5
		$groups = [];
305 5
		while ($row = $result->fetch()) {
306 5
			if (!isset($groups[(int) $row['announcement_id']])) {
307 5
				$groups[(int) $row['announcement_id']] = [];
308 5
			}
309 5
			$groups[(int) $row['announcement_id']][] = $row['gid'];
310 5
		}
311 5
		$result->closeCursor();
312
313 5
		return $returnSingleResult ? (array) array_pop($groups) : $groups;
314
	}
315
316
	/**
317
	 * @param string $message
318
	 * @return string
319
	 */
320 5
	protected function parseMessage($message) {
321 5
		return str_replace("\n", '<br />', str_replace(['<', '>'], ['&lt;', '&gt;'], $message));
322
	}
323
324
	/**
325
	 * @param string $subject
326
	 * @return string
327
	 */
328 5
	protected function parseSubject($subject) {
329 5
		return str_replace("\n", ' ', str_replace(['<', '>'], ['&lt;', '&gt;'], $subject));
330
	}
331
332
	/**
333
	 * Check if the user is in the admin group
334
	 * @return bool
335
	 */
336 5
	public function checkIsAdmin() {
337 5
		$user = $this->userSession->getUser();
338
339 5
		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...
340 4
			$groups = $this->getAdminGroups();
341 4
			foreach ($groups as $group) {
342 4
				return $this->groupManager->isInGroup($user->getUID(), $group);
343
			}
344
		}
345
346 1
		return false;
347
	}
348
349 8
	protected function getAdminGroups() {
350 8
		$adminGroups = $this->config->getAppValue('announcementcenter', 'admin_groups', '["admin"]');
351 8
		$adminGroups = json_decode($adminGroups, true);
352 8
		return $adminGroups;
353
	}
354
}
355