Completed
Push — master ( 586935...49b771 )
by Joas
14:13 queued 03:42
created

Manager   B

Complexity

Total Complexity 40

Size/Duplication

Total Lines 297
Duplicated Lines 4.04 %

Coupling/Cohesion

Components 1
Dependencies 0

Test Coverage

Coverage 98.87%

Importance

Changes 18
Bugs 2 Features 5
Metric Value
wmc 40
c 18
b 2
f 5
lcom 1
cbo 0
dl 12
loc 297
ccs 175
cts 177
cp 0.9887
rs 8.2608

11 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 6 1
B announce() 0 37 6
A addGroupLink() 0 9 1
A delete() 0 11 1
C getAnnouncement() 6 55 11
C getAnnouncements() 6 53 9
B getGroups() 0 24 5
A parseMessage() 0 3 1
A parseSubject() 0 3 1
A checkIsAdmin() 0 12 3
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\DB\QueryBuilder\IQueryBuilder;
27
use OCP\IConfig;
28
use OCP\IDBConnection;
29
use OCP\IGroupManager;
30
use OCP\IUser;
31
use OCP\IUserSession;
32
33
class Manager {
34
35
	/** @var IConfig */
36
	protected $config;
37
38
	/** @var IDBConnection */
39
	protected $connection;
40
41
	/** @var IGroupManager */
42
	protected $groupManager;
43
44
45
	/** @var IUserSession */
46
	protected $userSession;
47
48
	/**
49
	 * @param IConfig $config
50
	 * @param IDBConnection $connection
51
	 * @param IGroupManager $groupManager
52
	 * @param IUserSession $userSession
53
	 */
54 16
	public function __construct(IConfig $config, IDBConnection $connection, IGroupManager $groupManager, IUserSession $userSession) {
55 16
		$this->config = $config;
56 16
		$this->connection = $connection;
57 16
		$this->groupManager = $groupManager;
58 16
		$this->userSession = $userSession;
59 16
	}
60
61
	/**
62
	 * @param string $subject
63
	 * @param string $message
64
	 * @param string $user
65
	 * @param int $time
66
	 * @param string[] $groups
67
	 * @return array
68
	 * @throws \InvalidArgumentException when the subject is empty or invalid
69
	 */
70 7
	public function announce($subject, $message, $user, $time, array $groups) {
71 7
		$subject = trim($subject);
72 7
		$message = trim($message);
73 7
		if (isset($subject[512])) {
74 1
			throw new \InvalidArgumentException('Invalid subject', 1);
75
		}
76
77 6
		if ($subject === '') {
78 1
			throw new \InvalidArgumentException('Invalid subject', 2);
79
		}
80
81 5
		$queryBuilder = $this->connection->getQueryBuilder();
82 5
		$queryBuilder->insert('announcements')
83 5
			->values([
84 5
				'announcement_time' => $queryBuilder->createNamedParameter($time),
85 5
				'announcement_user' => $queryBuilder->createNamedParameter($user),
86 5
				'announcement_subject' => $queryBuilder->createNamedParameter($subject),
87 5
				'announcement_message' => $queryBuilder->createNamedParameter($message),
88 5
			]);
89 5
		$queryBuilder->execute();
90
91 5
		$id = $queryBuilder->getLastInsertId();
92
93 5
		$addedGroups = 0;
94 5
		foreach ($groups as $group) {
95 5
			if ($this->groupManager->groupExists($group)) {
96 4
				$this->addGroupLink((int) $id, $group);
97 4
				$addedGroups++;
98 4
			}
99 5
		}
100
101 5
		if ($addedGroups === 0) {
102 4
			$this->addGroupLink((int) $id, 'everyone');
103 4
		}
104
105 5
		return $this->getAnnouncement($id, true, true);
106
	}
107
108
	/**
109
	 * @param int $announcementId
110
	 * @param string $group
111
	 */
112 5
	protected function addGroupLink($announcementId, $group) {
113 5
		$query = $this->connection->getQueryBuilder();
114 5
		$query->insert('announcements_groups')
115 5
			->values([
116 5
				'announcement_id' => $query->createNamedParameter($announcementId),
117 5
				'gid' => $query->createNamedParameter($group),
118 5
			]);
119 5
		$query->execute();
120 5
	}
121
122
	/**
123
	 * @param int $id
124
	 */
125 5
	public function delete($id) {
126 5
		$query = $this->connection->getQueryBuilder();
127 5
		$query->delete('announcements')
128 5
			->where($query->expr()->eq('announcement_id', $query->createNamedParameter((int) $id)));
129 5
		$query->execute();
130
131 5
		$query = $this->connection->getQueryBuilder();
132 5
		$query->delete('announcements_groups')
133 5
			->where($query->expr()->eq('announcement_id', $query->createNamedParameter((int) $id)));
134 5
		$query->execute();
135 5
	}
136
137
	/**
138
	 * @param int $id
139
	 * @param bool $parseStrings
140
	 * @param bool $ignorePermissions
141
	 * @return array
142
	 * @throws \InvalidArgumentException when the id is invalid
143
	 */
144 6
	public function getAnnouncement($id, $parseStrings = true, $ignorePermissions = false) {
145 6
		if (!$ignorePermissions) {
146 4
			$user = $this->userSession->getUser();
147 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...
148 2
				$userGroups = $this->groupManager->getUserGroupIds($user);
149 2
				$userGroups[] = 'everyone';
150 2
			} else {
151 2
				$userGroups = ['everyone'];
152
			}
153 4
			$isInAdminGroups = array_intersect($this->getAdminGroups(), $userGroups);
154
155 4
			if (empty($isInAdminGroups)) {
156 3
				$query = $this->connection->getQueryBuilder();
157 3
				$query->select('*')
158 3
					->from('announcements_groups')
159 3
					->where($query->expr()->eq('announcement_id', $query->createNamedParameter((int) $id)))
160 3
					->andWhere($query->expr()->in('gid', $query->createNamedParameter($userGroups, IQueryBuilder::PARAM_STR_ARRAY)))
161 3
					->setMaxResults(1);
162 3
				$result = $query->execute();
163 3
				$entry = $result->fetch();
164 3
				$result->closeCursor();
165
166 3
				if (!$entry) {
167 3
					throw new \InvalidArgumentException('Invalid ID');
168
				}
169 2
			}
170 3
		}
171
172 5
		$queryBuilder = $this->connection->getQueryBuilder();
173 5
		$query = $queryBuilder->select('*')
174 5
			->from('announcements')
175 5
			->where($queryBuilder->expr()->eq('announcement_id', $queryBuilder->createParameter('id')))
176 5
			->setParameter('id', (int) $id);
177 5
		$result = $query->execute();
178 5
		$row = $result->fetch();
179 5
		$result->closeCursor();
180
181 5
		if ($row === false) {
182 3
			throw new \InvalidArgumentException('Invalid ID');
183
		}
184
185 5
		$groups = null;
186 5
		if ($ignorePermissions || (isset($isInAdminGroups) && !empty($isInAdminGroups))) {
187 5
			$groups = $this->getGroups($id);
188 5
		}
189
190
		return [
191 5
			'id'		=> (int) $row['announcement_id'],
192 5
			'author'	=> $row['announcement_user'],
193 5
			'time'		=> (int) $row['announcement_time'],
194 5
			'subject'	=> ($parseStrings) ? $this->parseSubject($row['announcement_subject']) : $row['announcement_subject'],
195 5
			'message'	=> ($parseStrings) ? $this->parseMessage($row['announcement_message']) : $row['announcement_message'],
196 5
			'groups'	=> $groups,
197 5
		];
198
	}
199
200
	/**
201
	 * @param int $limit
202
	 * @param int $offset
203
	 * @param bool $parseStrings
204
	 * @return array
205
	 */
206 3
	public function getAnnouncements($limit = 15, $offset = 0, $parseStrings = true) {
207 3
		$query = $this->connection->getQueryBuilder();
208 3
		$query->select('a.*')
209 3
			->from('announcements', 'a')
210 3
			->orderBy('a.announcement_time', 'DESC')
211 3
			->groupBy('a.announcement_id')
212 3
			->setMaxResults($limit);
213
214 3
		$user = $this->userSession->getUser();
215 3 View Code Duplication
		if ($user instanceof IUser) {
0 ignored issues
show
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...
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...
216 2
			$userGroups = $this->groupManager->getUserGroupIds($user);
217 2
			$userGroups[] = 'everyone';
218 2
		} else {
219 1
			$userGroups = ['everyone'];
220
		}
221
222 3
		$isInAdminGroups = array_intersect($this->getAdminGroups(), $userGroups);
223 3
		if (empty($isInAdminGroups)) {
224 2
			$query->leftJoin('a', 'announcements_groups', 'ag', $query->expr()->eq(
225 2
					'a.announcement_id', 'ag.announcement_id'
226 2
				))
227 2
				->andWhere($query->expr()->in('ag.gid', $query->createNamedParameter($userGroups, IQueryBuilder::PARAM_STR_ARRAY)));
228 2
		}
229
230 3
		if ($offset > 0) {
231 3
			$query->andWhere($query->expr()->lt('a.announcement_id', $query->createNamedParameter($offset, IQueryBuilder::PARAM_INT)));
232 3
		}
233
234 3
		$result = $query->execute();
235
236 3
		$announcements = [];
237 3
		while ($row = $result->fetch()) {
238 3
			$id = (int) $row['announcement_id'];
239 3
			$announcements[$id] = [
240 3
				'id'		=> $id,
241 3
				'author'	=> $row['announcement_user'],
242 3
				'time'		=> (int) $row['announcement_time'],
243 3
				'subject'	=> ($parseStrings) ? $this->parseSubject($row['announcement_subject']) : $row['announcement_subject'],
244 3
				'message'	=> ($parseStrings) ? $this->parseMessage($row['announcement_message']) : $row['announcement_message'],
245 3
				'groups'	=> null,
246
			];
247 3
		}
248 3
		$result->closeCursor();
249
250 3
		if (!empty($isInAdminGroups)) {
251 1
			$allGroups = $this->getGroups(array_keys($announcements));
252 1
			foreach ($allGroups as $id => $groups) {
253 1
				$announcements[$id]['groups'] = $groups;
254 1
			}
255 1
		}
256
257 3
		return $announcements;
258
	}
259
260
	/**
261
	 * Return the groups (or string everyone) which have access to the announcement(s)
262
	 *
263
	 * @param int|int[] $ids
264
	 * @return string[]|array[]
265
	 */
266 5
	public function getGroups($ids) {
267 5
		$returnSingleResult = false;
268 5
		if (is_int($ids)) {
269 5
			$ids = [$ids];
270 5
			$returnSingleResult = true;
271 5
		}
272
273 5
		$query = $this->connection->getQueryBuilder();
274 5
		$query->select('*')
275 5
			->from('announcements_groups')
276 5
			->where($query->expr()->in('announcement_id', $query->createNamedParameter($ids, IQueryBuilder::PARAM_INT_ARRAY)));
277 5
		$result = $query->execute();
278
279 5
		$groups = [];
280 5
		while ($row = $result->fetch()) {
281 5
			if (!isset($groups[(int) $row['announcement_id']])) {
282 5
				$groups[(int) $row['announcement_id']] = [];
283 5
			}
284 5
			$groups[(int) $row['announcement_id']][] = $row['gid'];
285 5
		}
286 5
		$result->closeCursor();
287
288 5
		return $returnSingleResult ? (array) array_pop($groups) : $groups;
289
	}
290
291
	/**
292
	 * @param string $message
293
	 * @return string
294
	 */
295 5
	protected function parseMessage($message) {
296 5
		return str_replace("\n", '<br />', str_replace(['<', '>'], ['&lt;', '&gt;'], $message));
297
	}
298
299
	/**
300
	 * @param string $subject
301
	 * @return string
302
	 */
303 5
	protected function parseSubject($subject) {
304 5
		return str_replace("\n", ' ', str_replace(['<', '>'], ['&lt;', '&gt;'], $subject));
305
	}
306
307
	/**
308
	 * Check if the user is in the admin group
309
	 * @return bool
310
	 */
311 5
	public function checkIsAdmin() {
312 5
		$user = $this->userSession->getUser();
313
314 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...
315 4
			$groups = $this->getAdminGroups();
316 4
			foreach ($groups as $group) {
317 4
				return $this->groupManager->isInGroup($user->getUID(), $group);
318
			}
319
		}
320
321 1
		return false;
322
	}
323
324 8
	protected function getAdminGroups() {
325 8
		$adminGroups = $this->config->getAppValue('announcementcenter', 'admin_groups', '["admin"]');
326 8
		$adminGroups = json_decode($adminGroups, true);
327 8
		return $adminGroups;
328
	}
329
}
330