Completed
Pull Request — master (#8)
by Joas
04:40
created

Manager::getGroups()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 15
Code Lines 11

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 12
CRAP Score 2

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 15
ccs 12
cts 12
cp 1
rs 9.4285
cc 2
eloc 11
nc 2
nop 1
crap 2
1
<?php
2
/**
3
 * @author Joas Schilling <[email protected]>
4
 *
5
 * @copyright Copyright (c) 2016, Joas Schilling <[email protected]>
6
 * @license AGPL-3.0
7
 *
8
 * This code is free software: you can redistribute it and/or modify
9
 * it under the terms of the GNU Affero General Public License, version 3,
10
 * as published by the Free Software Foundation.
11
 *
12
 * This program is distributed in the hope that it will be useful,
13
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15
 * GNU Affero General Public License for more details.
16
 *
17
 * You should have received a copy of the GNU Affero General Public License, version 3,
18
 * along with this program.  If not, see <http://www.gnu.org/licenses/>
19
 *
20
 */
21
22
namespace OCA\AnnouncementCenter;
23
24
use OCP\DB\QueryBuilder\IQueryBuilder;
25
use OCP\IDBConnection;
26
use OCP\IGroupManager;
27
use OCP\IUser;
28
use OCP\IUserSession;
29
30
class Manager {
31
32
	/** @var IDBConnection */
33
	private $connection;
34
35
	/** @var IGroupManager */
36
	private $groupManager;
37
38
39
	/** @var IUserSession */
40
	private $userSession;
41
42
	/**
43
	 * @param IDBConnection $connection
44
	 * @param IGroupManager $groupManager
45
	 * @param IUserSession $userSession
46
	 */
47 10
	public function __construct(IDBConnection $connection, IGroupManager $groupManager, IUserSession $userSession) {
48 10
		$this->connection = $connection;
49 10
		$this->groupManager = $groupManager;
50 10
		$this->userSession = $userSession;
51 10
	}
52
53
	/**
54
	 * @param string $subject
55
	 * @param string $message
56
	 * @param string $user
57
	 * @param int $time
58
	 * @param string[] $groups
59
	 * @return array
60
	 * @throws \InvalidArgumentException when the subject is empty or invalid
61
	 */
62 6
	public function announce($subject, $message, $user, $time, array $groups) {
63 6
		$subject = trim($subject);
64 6
		$message = trim($message);
65 6
		if (isset($subject[512])) {
66 1
			throw new \InvalidArgumentException('Invalid subject', 1);
67
		}
68
69 5
		if ($subject === '') {
70 1
			throw new \InvalidArgumentException('Invalid subject', 2);
71
		}
72
73 4
		$queryBuilder = $this->connection->getQueryBuilder();
74 4
		$queryBuilder->insert('announcements')
75 4
			->values([
76 4
				'announcement_time' => $queryBuilder->createParameter('time'),
77 4
				'announcement_user' => $queryBuilder->createParameter('user'),
78 4
				'announcement_subject' => $queryBuilder->createParameter('subject'),
79 4
				'announcement_message' => $queryBuilder->createParameter('message'),
80 4
			])
81 4
			->setParameter('time', $time)
82 4
			->setParameter('user', $user)
83 4
			->setParameter('subject', $subject)
84 4
			->setParameter('message', $message);
85 4
		$queryBuilder->execute();
86
87 4
		$queryBuilder = $this->connection->getQueryBuilder();
88 4
		$query = $queryBuilder->select('*')
89 4
			->from('announcements')
90 4
			->where($queryBuilder->expr()->eq('announcement_time', $queryBuilder->createParameter('time')))
91 4
			->andWhere($queryBuilder->expr()->eq('announcement_user', $queryBuilder->createParameter('user')))
92 4
			->orderBy('announcement_id', 'DESC')
93 4
			->setParameter('time', (int) $time)
94 4
			->setParameter('user', $user);
95 4
		$result = $query->execute();
96 4
		$row = $result->fetch();
97 4
		$result->closeCursor();
98
99 4
		$addedGroups = 0;
100 4
		foreach ($groups as $group) {
101 4
			if ($this->groupManager->groupExists($group)) {
102 3
				$this->addGroupLink((int) $row['announcement_id'], $group);
103 3
				$addedGroups++;
104 3
			}
105 4
		}
106
107 4
		if ($addedGroups === 0) {
108 3
			$this->addGroupLink((int) $row['announcement_id'], 'everyone');
109 3
		}
110
111
		return [
112 4
			'id'		=> (int) $row['announcement_id'],
113 4
			'author'	=> $row['announcement_user'],
114 4
			'time'		=> (int) $row['announcement_time'],
115 4
			'subject'	=> $this->parseSubject($row['announcement_subject']),
116 4
			'message'	=> $this->parseMessage($row['announcement_message']),
117 4
		];
118
	}
119
120
	/**
121
	 * @param int $announcementId
122
	 * @param string $group
123
	 */
124 4
	protected function addGroupLink($announcementId, $group) {
125 4
		$query = $this->connection->getQueryBuilder();
126 4
		$query->insert('announcements_groups')
127 4
			->values([
128 4
				'announcement_id' => $query->createNamedParameter($announcementId),
129 4
				'gid' => $query->createNamedParameter($group),
130 4
			]);
131 4
		$query->execute();
132 4
	}
133
134
	/**
135
	 * @param int $id
136
	 */
137 3
	public function delete($id) {
138 3
		$query = $this->connection->getQueryBuilder();
139 3
		$query->delete('announcements')
140 3
			->where($query->expr()->eq('announcement_id', $query->createNamedParameter((int) $id)));
141 3
		$query->execute();
142
143 3
		$query = $this->connection->getQueryBuilder();
144 3
		$query->delete('announcements_groups')
145 3
			->where($query->expr()->eq('announcement_id', $query->createNamedParameter((int) $id)));
146 3
		$query->execute();
147 3
	}
148
149
	/**
150
	 * @param int $id
151
	 * @param bool $parseStrings
152
	 * @param bool $ignorePermissions
153
	 * @return array
154
	 * @throws \InvalidArgumentException when the id is invalid
155
	 */
156 3
	public function getAnnouncement($id, $parseStrings = true, $ignorePermissions = false) {
157 3
		if (!$ignorePermissions) {
158 3
			$user = $this->userSession->getUser();
159 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...
160 1
				$groups = $this->groupManager->getUserGroupIds($user);
161 1
				$groups[] = 'everyone';
162 1
			} else {
163 2
				$groups = ['everyone'];
164
			}
165
166 3
			if (!in_array('admin', $groups)) {
167 3
				$query = $this->connection->getQueryBuilder();
168 3
				$query->select('*')
169 3
					->from('announcements_groups')
170 3
					->where($query->expr()->eq('announcement_id', $query->createNamedParameter((int) $id)))
171 3
					->andWhere($query->expr()->in('gid', $query->createNamedParameter($groups, IQueryBuilder::PARAM_STR_ARRAY)))
172 3
					->setMaxResults(1);
173 3
				$result = $query->execute();
174 3
				$entry = $result->fetch();
175 3
				$result->closeCursor();
176
177 3
				if (!$entry) {
178 2
					throw new \InvalidArgumentException('Invalid ID');
179
				}
180 2
			}
181 2
		}
182
183 2
		$queryBuilder = $this->connection->getQueryBuilder();
184 2
		$query = $queryBuilder->select('*')
185 2
			->from('announcements')
186 2
			->where($queryBuilder->expr()->eq('announcement_id', $queryBuilder->createParameter('id')))
187 2
			->setParameter('id', (int) $id);
188 2
		$result = $query->execute();
189 2
		$row = $result->fetch();
190 2
		$result->closeCursor();
191
192 2
		if ($row === false) {
193 1
			throw new \InvalidArgumentException('Invalid ID');
194
		}
195
196
		return [
197 2
			'id'		=> (int) $row['announcement_id'],
198 2
			'author'	=> $row['announcement_user'],
199 2
			'time'		=> (int) $row['announcement_time'],
200 2
			'subject'	=> ($parseStrings) ? $this->parseSubject($row['announcement_subject']) : $row['announcement_subject'],
201 2
			'message'	=> ($parseStrings) ? $this->parseMessage($row['announcement_message']) : $row['announcement_message'],
202 2
		];
203
	}
204
205
	/**
206
	 * @param int $limit
207
	 * @param int $offset
208
	 * @param bool $parseStrings
209
	 * @return array
210
	 */
211 2
	public function getAnnouncements($limit = 15, $offset = 0, $parseStrings = true) {
212 2
		$query = $this->connection->getQueryBuilder();
213 2
		$query->select('a.*')
214 2
			->from('announcements', 'a')
215 2
			->orderBy('a.announcement_time', 'DESC')
216 2
			->groupBy('a.announcement_id')
217 2
			->setMaxResults($limit);
218
219 2
		$user = $this->userSession->getUser();
220 2 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...
221 1
			$groups = $this->groupManager->getUserGroupIds($user);
222 1
			$groups[] = 'everyone';
223 1
		} else {
224 1
			$groups = ['everyone'];
225
		}
226
227 2
		if (!in_array('admin', $groups)) {
228 2
			$query->leftJoin('a', 'announcements_groups', 'ag', $query->expr()->eq(
229 2
					'a.announcement_id', 'ag.announcement_id'
230 2
				))
231 2
				->andWhere($query->expr()->in('ag.gid', $query->createNamedParameter($groups, IQueryBuilder::PARAM_STR_ARRAY)));
232 2
		}
233
234 2
		if ($offset > 0) {
235
			$query->andWhere($query->expr()->lt('a.announcement_id', $query->createNamedParameter($offset, IQueryBuilder::PARAM_INT)));
236
		}
237
238 2
		$result = $query->execute();
239
240
241 2
		$announcements = [];
242 2
		while ($row = $result->fetch()) {
243 2
			$announcements[] = [
244 2
				'id'		=> (int) $row['announcement_id'],
245 2
				'author'	=> $row['announcement_user'],
246 2
				'time'		=> (int) $row['announcement_time'],
247 2
				'subject'	=> ($parseStrings) ? $this->parseSubject($row['announcement_subject']) : $row['announcement_subject'],
248 2
				'message'	=> ($parseStrings) ? $this->parseMessage($row['announcement_message']) : $row['announcement_message'],
249
			];
250 2
		}
251 2
		$result->closeCursor();
252
253
254 2
		return $announcements;
255
	}
256
257
	/**
258
	 * Return the groups (or string everyone) which have access to the announcement
259
	 *
260
	 * @param int $id
261
	 * @return string[]
262
	 */
263 3
	public function getGroups($id) {
264 3
		$query = $this->connection->getQueryBuilder();
265 3
		$query->select('gid')
266 3
			->from('announcements_groups')
267 3
			->where($query->expr()->eq('announcement_id', $query->createNamedParameter($id)));
268 3
		$result = $query->execute();
269
270 3
		$groups = [];
271 3
		while ($row = $result->fetch()) {
272 3
			$groups[] = $row['gid'];
273 3
		}
274 3
		$result->closeCursor();
275
276 3
		return $groups;
277
	}
278
279
	/**
280
	 * @param string $message
281
	 * @return string
282
	 */
283 4
	protected function parseMessage($message) {
284 4
		return str_replace("\n", '<br />', str_replace(['<', '>'], ['&lt;', '&gt;'], $message));
285
	}
286
287
	/**
288
	 * @param string $subject
289
	 * @return string
290
	 */
291 4
	protected function parseSubject($subject) {
292 4
		return str_replace("\n", ' ', str_replace(['<', '>'], ['&lt;', '&gt;'], $subject));
293
	}
294
}
295