Completed
Pull Request — master (#9)
by Joas
02:30
created

Manager   B

Complexity

Total Complexity 39

Size/Duplication

Total Lines 290
Duplicated Lines 4.14 %

Coupling/Cohesion

Components 1
Dependencies 0

Test Coverage

Coverage 100%

Importance

Changes 17
Bugs 2 Features 4
Metric Value
wmc 39
c 17
b 2
f 4
lcom 1
cbo 0
dl 12
loc 290
ccs 169
cts 169
cp 1
rs 8.2857

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 54 11
C getAnnouncements() 6 52 9
B getGroups() 0 24 5
A parseMessage() 0 3 1
A parseSubject() 0 3 1
A checkIsAdmin() 0 9 2
A getAdminGroupName() 0 3 1

How to fix   Duplicated Code   

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:

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\IConfig;
26
use OCP\IDBConnection;
27
use OCP\IGroupManager;
28
use OCP\IUser;
29
use OCP\IUserSession;
30
31
class Manager {
32
33
	/** @var IConfig */
34
	protected $config;
35
36
	/** @var IDBConnection */
37
	protected $connection;
38
39
	/** @var IGroupManager */
40
	protected $groupManager;
41
42
43
	/** @var IUserSession */
44
	protected $userSession;
45
46
	/**
47
	 * @param IConfig $config
48
	 * @param IDBConnection $connection
49
	 * @param IGroupManager $groupManager
50
	 * @param IUserSession $userSession
51
	 */
52 16
	public function __construct(IConfig $config, IDBConnection $connection, IGroupManager $groupManager, IUserSession $userSession) {
53 16
		$this->config = $config;
54 16
		$this->connection = $connection;
55 16
		$this->groupManager = $groupManager;
56 16
		$this->userSession = $userSession;
57 16
	}
58
59
	/**
60
	 * @param string $subject
61
	 * @param string $message
62
	 * @param string $user
63
	 * @param int $time
64
	 * @param string[] $groups
65
	 * @return array
66
	 * @throws \InvalidArgumentException when the subject is empty or invalid
67
	 */
68 7
	public function announce($subject, $message, $user, $time, array $groups) {
69 7
		$subject = trim($subject);
70 7
		$message = trim($message);
71 7
		if (isset($subject[512])) {
72 1
			throw new \InvalidArgumentException('Invalid subject', 1);
73
		}
74
75 6
		if ($subject === '') {
76 1
			throw new \InvalidArgumentException('Invalid subject', 2);
77
		}
78
79 5
		$queryBuilder = $this->connection->getQueryBuilder();
80 5
		$queryBuilder->insert('announcements')
81 5
			->values([
82 5
				'announcement_time' => $queryBuilder->createNamedParameter($time),
83 5
				'announcement_user' => $queryBuilder->createNamedParameter($user),
84 5
				'announcement_subject' => $queryBuilder->createNamedParameter($subject),
85 5
				'announcement_message' => $queryBuilder->createNamedParameter($message),
86 5
			]);
87 5
		$queryBuilder->execute();
88
89 5
		$id = $queryBuilder->getLastInsertId();
90
91 5
		$addedGroups = 0;
92 5
		foreach ($groups as $group) {
93 5
			if ($this->groupManager->groupExists($group)) {
94 4
				$this->addGroupLink((int) $id, $group);
95 4
				$addedGroups++;
96 4
			}
97 5
		}
98
99 5
		if ($addedGroups === 0) {
100 4
			$this->addGroupLink((int) $id, 'everyone');
101 4
		}
102
103 5
		return $this->getAnnouncement($id, true, true);
104
	}
105
106
	/**
107
	 * @param int $announcementId
108
	 * @param string $group
109
	 */
110 5
	protected function addGroupLink($announcementId, $group) {
111 5
		$query = $this->connection->getQueryBuilder();
112 5
		$query->insert('announcements_groups')
113 5
			->values([
114 5
				'announcement_id' => $query->createNamedParameter($announcementId),
115 5
				'gid' => $query->createNamedParameter($group),
116 5
			]);
117 5
		$query->execute();
118 5
	}
119
120
	/**
121
	 * @param int $id
122
	 */
123 5
	public function delete($id) {
124 5
		$query = $this->connection->getQueryBuilder();
125 5
		$query->delete('announcements')
126 5
			->where($query->expr()->eq('announcement_id', $query->createNamedParameter((int) $id)));
127 5
		$query->execute();
128
129 5
		$query = $this->connection->getQueryBuilder();
130 5
		$query->delete('announcements_groups')
131 5
			->where($query->expr()->eq('announcement_id', $query->createNamedParameter((int) $id)));
132 5
		$query->execute();
133 5
	}
134
135
	/**
136
	 * @param int $id
137
	 * @param bool $parseStrings
138
	 * @param bool $ignorePermissions
139
	 * @return array
140
	 * @throws \InvalidArgumentException when the id is invalid
141
	 */
142 6
	public function getAnnouncement($id, $parseStrings = true, $ignorePermissions = false) {
143 6
		if (!$ignorePermissions) {
144 4
			$user = $this->userSession->getUser();
145 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...
146 2
				$userGroups = $this->groupManager->getUserGroupIds($user);
147 2
				$userGroups[] = 'everyone';
148 2
			} else {
149 2
				$userGroups = ['everyone'];
150
			}
151
152 4
			if (!in_array($this->getAdminGroupName(), $userGroups)) {
153 3
				$query = $this->connection->getQueryBuilder();
154 3
				$query->select('*')
155 3
					->from('announcements_groups')
156 3
					->where($query->expr()->eq('announcement_id', $query->createNamedParameter((int) $id)))
157 3
					->andWhere($query->expr()->in('gid', $query->createNamedParameter($userGroups, IQueryBuilder::PARAM_STR_ARRAY)))
158 3
					->setMaxResults(1);
159 3
				$result = $query->execute();
160 3
				$entry = $result->fetch();
161 3
				$result->closeCursor();
162
163 3
				if (!$entry) {
164 3
					throw new \InvalidArgumentException('Invalid ID');
165
				}
166 2
			}
167 3
		}
168
169 5
		$queryBuilder = $this->connection->getQueryBuilder();
170 5
		$query = $queryBuilder->select('*')
171 5
			->from('announcements')
172 5
			->where($queryBuilder->expr()->eq('announcement_id', $queryBuilder->createParameter('id')))
173 5
			->setParameter('id', (int) $id);
174 5
		$result = $query->execute();
175 5
		$row = $result->fetch();
176 5
		$result->closeCursor();
177
178 5
		if ($row === false) {
179 3
			throw new \InvalidArgumentException('Invalid ID');
180
		}
181
182 5
		$groups = null;
183 5
		if ($ignorePermissions || (isset($userGroups) && in_array($this->getAdminGroupName(), $userGroups))) {
0 ignored issues
show
Bug introduced by
The variable $userGroups does not seem to be defined for all execution paths leading up to this point.

If you define a variable conditionally, it can happen that it is not defined for all execution paths.

Let’s take a look at an example:

function myFunction($a) {
    switch ($a) {
        case 'foo':
            $x = 1;
            break;

        case 'bar':
            $x = 2;
            break;
    }

    // $x is potentially undefined here.
    echo $x;
}

In the above example, the variable $x is defined if you pass “foo” or “bar” as argument for $a. However, since the switch statement has no default case statement, if you pass any other value, the variable $x would be undefined.

Available Fixes

  1. Check for existence of the variable explicitly:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        if (isset($x)) { // Make sure it's always set.
            echo $x;
        }
    }
    
  2. Define a default value for the variable:

    function myFunction($a) {
        $x = ''; // Set a default which gets overridden for certain paths.
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        echo $x;
    }
    
  3. Add a value for the missing path:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
    
            // We add support for the missing case.
            default:
                $x = '';
                break;
        }
    
        echo $x;
    }
    
Loading history...
184 5
			$groups = $this->getGroups($id);
185 5
		}
186
187
		return [
188 5
			'id'		=> (int) $row['announcement_id'],
189 5
			'author'	=> $row['announcement_user'],
190 5
			'time'		=> (int) $row['announcement_time'],
191 5
			'subject'	=> ($parseStrings) ? $this->parseSubject($row['announcement_subject']) : $row['announcement_subject'],
192 5
			'message'	=> ($parseStrings) ? $this->parseMessage($row['announcement_message']) : $row['announcement_message'],
193 5
			'groups'	=> $groups,
194 5
		];
195
	}
196
197
	/**
198
	 * @param int $limit
199
	 * @param int $offset
200
	 * @param bool $parseStrings
201
	 * @return array
202
	 */
203 3
	public function getAnnouncements($limit = 15, $offset = 0, $parseStrings = true) {
204 3
		$query = $this->connection->getQueryBuilder();
205 3
		$query->select('a.*')
206 3
			->from('announcements', 'a')
207 3
			->orderBy('a.announcement_time', 'DESC')
208 3
			->groupBy('a.announcement_id')
209 3
			->setMaxResults($limit);
210
211 3
		$user = $this->userSession->getUser();
212 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...
213 2
			$userGroups = $this->groupManager->getUserGroupIds($user);
214 2
			$userGroups[] = 'everyone';
215 2
		} else {
216 1
			$userGroups = ['everyone'];
217
		}
218
219 3
		if (!in_array($this->getAdminGroupName(), $userGroups)) {
220 2
			$query->leftJoin('a', 'announcements_groups', 'ag', $query->expr()->eq(
221 2
					'a.announcement_id', 'ag.announcement_id'
222 2
				))
223 2
				->andWhere($query->expr()->in('ag.gid', $query->createNamedParameter($userGroups, IQueryBuilder::PARAM_STR_ARRAY)));
224 2
		}
225
226 3
		if ($offset > 0) {
227 3
			$query->andWhere($query->expr()->lt('a.announcement_id', $query->createNamedParameter($offset, IQueryBuilder::PARAM_INT)));
228 3
		}
229
230 3
		$result = $query->execute();
231
232 3
		$announcements = [];
233 3
		while ($row = $result->fetch()) {
234 3
			$id = (int) $row['announcement_id'];
235 3
			$announcements[$id] = [
236 3
				'id'		=> $id,
237 3
				'author'	=> $row['announcement_user'],
238 3
				'time'		=> (int) $row['announcement_time'],
239 3
				'subject'	=> ($parseStrings) ? $this->parseSubject($row['announcement_subject']) : $row['announcement_subject'],
240 3
				'message'	=> ($parseStrings) ? $this->parseMessage($row['announcement_message']) : $row['announcement_message'],
241 3
				'groups'	=> null,
242
			];
243 3
		}
244 3
		$result->closeCursor();
245
246 3
		if (in_array($this->getAdminGroupName(), $userGroups)) {
247 1
			$allGroups = $this->getGroups(array_keys($announcements));
248 1
			foreach ($allGroups as $id => $groups) {
249 1
				$announcements[$id]['groups'] = $groups;
250 1
			}
251 1
		}
252
253 3
		return $announcements;
254
	}
255
256
	/**
257
	 * Return the groups (or string everyone) which have access to the announcement(s)
258
	 *
259
	 * @param int|int[] $ids
260
	 * @return string[]|array[]
261
	 */
262 5
	public function getGroups($ids) {
263 5
		$returnSingleResult = false;
264 5
		if (is_int($ids)) {
265 5
			$ids = [$ids];
266 5
			$returnSingleResult = true;
267 5
		}
268
269 5
		$query = $this->connection->getQueryBuilder();
270 5
		$query->select('*')
271 5
			->from('announcements_groups')
272 5
			->where($query->expr()->in('announcement_id', $query->createNamedParameter($ids, IQueryBuilder::PARAM_INT_ARRAY)));
273 5
		$result = $query->execute();
274
275 5
		$groups = [];
276 5
		while ($row = $result->fetch()) {
277 5
			if (!isset($groups[(int) $row['announcement_id']])) {
278 5
				$groups[(int) $row['announcement_id']] = [];
279 5
			}
280 5
			$groups[(int) $row['announcement_id']][] = $row['gid'];
281 5
		}
282 5
		$result->closeCursor();
283
284 5
		return $returnSingleResult ? (array) array_pop($groups) : $groups;
285
	}
286
287
	/**
288
	 * @param string $message
289
	 * @return string
290
	 */
291 5
	protected function parseMessage($message) {
292 5
		return str_replace("\n", '<br />', str_replace(['<', '>'], ['&lt;', '&gt;'], $message));
293
	}
294
295
	/**
296
	 * @param string $subject
297
	 * @return string
298
	 */
299 5
	protected function parseSubject($subject) {
300 5
		return str_replace("\n", ' ', str_replace(['<', '>'], ['&lt;', '&gt;'], $subject));
301
	}
302
303
	/**
304
	 * Check if the user is in the admin group
305
	 * @return bool
306
	 */
307 5
	public function checkIsAdmin() {
308 5
		$user = $this->userSession->getUser();
309
310 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...
311 4
			return $this->groupManager->isInGroup($user->getUID(), $this->getAdminGroupName());
312
		}
313
314 1
		return false;
315
	}
316
317 8
	protected function getAdminGroupName() {
318 8
		return $this->config->getAppValue('announcementcenter', 'admin_group', 'admin');
319
	}
320
}
321