Completed
Pull Request — master (#8)
by Joas
40:02 queued 37:57
created

Manager::getAnnouncement()   C

Complexity

Conditions 8
Paths 27

Size

Total Lines 48
Code Lines 36

Duplication

Lines 6
Ratio 12.5 %

Code Coverage

Tests 0
CRAP Score 72

Importance

Changes 6
Bugs 1 Features 1
Metric Value
c 6
b 1
f 1
dl 6
loc 48
ccs 0
cts 38
cp 0
rs 5.9322
cc 8
eloc 36
nc 27
nop 3
crap 72
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 3
	public function __construct(IDBConnection $connection, IGroupManager $groupManager, IUserSession $userSession) {
48 3
		$this->connection = $connection;
49 3
		$this->groupManager = $groupManager;
50 3
		$this->userSession = $userSession;
51 3
	}
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
	public function announce($subject, $message, $user, $time, array $groups) {
63
		$subject = trim($subject);
64
		$message = trim($message);
65
		if (isset($subject[512])) {
66
			throw new \InvalidArgumentException('Invalid subject', 1);
67
		}
68
69
		if ($subject === '') {
70
			throw new \InvalidArgumentException('Invalid subject', 2);
71
		}
72
73
		$queryBuilder = $this->connection->getQueryBuilder();
74
		$queryBuilder->insert('announcements')
75
			->values([
76
				'announcement_time' => $queryBuilder->createParameter('time'),
77
				'announcement_user' => $queryBuilder->createParameter('user'),
78
				'announcement_subject' => $queryBuilder->createParameter('subject'),
79
				'announcement_message' => $queryBuilder->createParameter('message'),
80
			])
81
			->setParameter('time', $time)
82
			->setParameter('user', $user)
83
			->setParameter('subject', $subject)
84
			->setParameter('message', $message);
85
		$queryBuilder->execute();
86
87
		$queryBuilder = $this->connection->getQueryBuilder();
88
		$query = $queryBuilder->select('*')
89
			->from('announcements')
90
			->where($queryBuilder->expr()->eq('announcement_time', $queryBuilder->createParameter('time')))
91
			->andWhere($queryBuilder->expr()->eq('announcement_user', $queryBuilder->createParameter('user')))
92
			->orderBy('announcement_id', 'DESC')
93
			->setParameter('time', (int) $time)
94
			->setParameter('user', $user);
95
		$result = $query->execute();
96
		$row = $result->fetch();
97
		$result->closeCursor();
98
99
		$addedGroups = 0;
100
		foreach ($groups as $group) {
101
			if ($this->groupManager->groupExists($group)) {
102
				$this->addGroupLink((int) $row['announcement_id'], $group);
103
				$addedGroups++;
104
			}
105
		}
106
107
		if ($addedGroups === 0) {
108
			$this->addGroupLink((int) $row['announcement_id'], 'everyone');
109
		}
110
111
		return [
112
			'id'		=> (int) $row['announcement_id'],
113
			'author'	=> $row['announcement_user'],
114
			'time'		=> (int) $row['announcement_time'],
115
			'subject'	=> $this->parseSubject($row['announcement_subject']),
116
			'message'	=> $this->parseMessage($row['announcement_message']),
117
		];
118
	}
119
120
	/**
121
	 * @param int $announcementId
122
	 * @param string $group
123
	 */
124
	protected function addGroupLink($announcementId, $group) {
125
		$query = $this->connection->getQueryBuilder();
126
		$query->insert('announcements_groups')
127
			->values([
128
				'announcement_id' => $query->createNamedParameter($announcementId),
129
				'gid' => $query->createNamedParameter($group),
130
			]);
131
		$query->execute();
132
	}
133
134
	/**
135
	 * @param int $id
136
	 */
137
	public function delete($id) {
138
		$query = $this->connection->getQueryBuilder();
139
		$query->delete('announcements')
140
			->where($query->expr()->eq('announcement_id', $query->createNamedParameter((int) $id)));
141
		$query->execute();
142
143
		$query = $this->connection->getQueryBuilder();
144
		$query->delete('announcements_groups')
145
			->where($query->expr()->eq('announcement_id', $query->createNamedParameter((int) $id)));
146
		$query->execute();
147
	}
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
	public function getAnnouncement($id, $parseStrings = true, $ignorePermissions = false) {
157
		if (!$ignorePermissions) {
158
			$user = $this->userSession->getUser();
159 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
				$groups = $this->groupManager->getUserGroupIds($user);
161
				$groups[] = 'everyone';
162
			} else {
163
				$groups = ['everyone'];
164
			}
165
166
			if (!in_array('admin', $groups)) {
167
				$query = $this->connection->getQueryBuilder();
168
				$query->select('*')
169
					->from('announcements_groups')
170
					->where($query->expr()->eq('announcement_id', $query->createNamedParameter((int) $id)))
171
					->andWhere($query->expr()->in('gid', $query->createNamedParameter($groups, IQueryBuilder::PARAM_STR_ARRAY)))
172
					->setMaxResults(1);
173
				$result = $query->execute();
174
				$entry = $result->fetch();
175
				$result->closeCursor();
176
177
				if ($entry === null) {
178
					throw new \InvalidArgumentException('Invalid ID');
179
				}
180
			}
181
		}
182
183
		$queryBuilder = $this->connection->getQueryBuilder();
184
		$query = $queryBuilder->select('*')
185
			->from('announcements')
186
			->where($queryBuilder->expr()->eq('announcement_id', $queryBuilder->createParameter('id')))
187
			->setParameter('id', (int) $id);
188
		$result = $query->execute();
189
		$row = $result->fetch();
190
		$result->closeCursor();
191
192
		if ($row === false) {
193
			throw new \InvalidArgumentException('Invalid ID');
194
		}
195
196
		return [
197
			'id'		=> (int) $row['announcement_id'],
198
			'author'	=> $row['announcement_user'],
199
			'time'		=> (int) $row['announcement_time'],
200
			'subject'	=> ($parseStrings) ? $this->parseSubject($row['announcement_subject']) : $row['announcement_subject'],
201
			'message'	=> ($parseStrings) ? $this->parseMessage($row['announcement_message']) : $row['announcement_message'],
202
		];
203
	}
204
205
	/**
206
	 * @param int $limit
207
	 * @param int $offset
208
	 * @param bool $parseStrings
209
	 * @return array
210
	 */
211
	public function getAnnouncements($limit = 15, $offset = 0, $parseStrings = true) {
212
		$query = $this->connection->getQueryBuilder();
213
		$query->select('a.*')
214
			->from('announcements', 'a')
215
			->orderBy('a.announcement_time', 'DESC')
216
			->setMaxResults($limit);
217
218
		$user = $this->userSession->getUser();
219 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...
220
			$groups = $this->groupManager->getUserGroupIds($user);
221
			$groups[] = 'everyone';
222
		} else {
223
			$groups = ['everyone'];
224
		}
225
226
		if (!in_array('admin', $groups)) {
227
			$query->leftJoin('a', 'announcements_groups', 'ag', $query->expr()->eq(
228
				'a.announcement_id', 'ag.announcement_id'
229
			))
230
				->andWhere($query->expr()->in('ag.gid', $query->createNamedParameter($groups, IQueryBuilder::PARAM_STR_ARRAY)));
231
		}
232
233
		if ($offset > 0) {
234
			$query->andWhere($query->expr()->lt('a.announcement_id', $query->createNamedParameter($offset, IQueryBuilder::PARAM_INT)));
235
		}
236
237
		$result = $query->execute();
238
239
240
		$announcements = [];
241
		while ($row = $result->fetch()) {
242
			$announcements[] = [
243
				'id'		=> (int) $row['announcement_id'],
244
				'author'	=> $row['announcement_user'],
245
				'time'		=> (int) $row['announcement_time'],
246
				'subject'	=> ($parseStrings) ? $this->parseSubject($row['announcement_subject']) : $row['announcement_subject'],
247
				'message'	=> ($parseStrings) ? $this->parseMessage($row['announcement_message']) : $row['announcement_message'],
248
			];
249
		}
250
		$result->closeCursor();
251
252
253
		return $announcements;
254
	}
255
256
	/**
257
	 * @param string $message
258
	 * @return string
259
	 */
260
	protected function parseMessage($message) {
261
		return str_replace("\n", '<br />', str_replace(['<', '>'], ['&lt;', '&gt;'], $message));
262
	}
263
264
	/**
265
	 * @param string $subject
266
	 * @return string
267
	 */
268
	protected function parseSubject($subject) {
269
		return str_replace("\n", ' ', str_replace(['<', '>'], ['&lt;', '&gt;'], $subject));
270
	}
271
}
272