Completed
Push — testscrut1 ( 887503...5550f6 )
by Maxence
02:18
created

CirclesMapper::create()   C

Complexity

Conditions 8
Paths 11

Size

Total Lines 64
Code Lines 39

Duplication

Lines 0
Ratio 0 %

Importance

Changes 3
Bugs 0 Features 0
Metric Value
dl 0
loc 64
rs 6.8232
c 3
b 0
f 0
cc 8
eloc 39
nc 11
nop 2

How to fix   Long Method   

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
 * Circles - Bring cloud-users closer together.
4
 *
5
 * This file is licensed under the Affero General Public License version 3 or
6
 * later. See the COPYING file.
7
 *
8
 * @author Maxence Lange <[email protected]>
9
 * @copyright 2017
10
 * @license GNU AGPL version 3 or any later version
11
 *
12
 * This program is free software: you can redistribute it and/or modify
13
 * it under the terms of the GNU Affero General Public License as
14
 * published by the Free Software Foundation, either version 3 of the
15
 * License, or (at your option) any later version.
16
 *
17
 * This program is distributed in the hope that it will be useful,
18
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
19
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
20
 * GNU Affero General Public License for more details.
21
 *
22
 * You should have received a copy of the GNU Affero General Public License
23
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
24
 *
25
 */
26
27
namespace OCA\Circles\Db;
28
29
use OCA\Circles\Exceptions\CircleAlreadyExistsException;
30
use OCA\Circles\Exceptions\CircleCreationException;
31
use OCA\Circles\Exceptions\CircleDoesNotExistException;
32
use OCA\Circles\Exceptions\ConfigNoCircleAvailable;
33
use OCA\Circles\Model\Circle;
34
use OCA\Circles\Model\Member;
35
36
use OCP\IDBConnection;
37
use OCP\AppFramework\Db\Mapper;
38
39
class CirclesMapper extends Mapper {
40
41
	const TABLENAME = 'circles_circles';
42
43
	private $miscService;
44
45
	public function __construct(IDBConnection $db, $miscService) {
46
		parent::__construct($db, self::TABLENAME, 'OCA\Circles\Db\Circles');
47
		$this->miscService = $miscService;
48
49
	}
50
51
52
	/**
53
	 * Returns all circle from a user point-of-view
54
	 *
55
	 * @param $userId
56
	 * @param $type
57
	 * @param string $name
58
	 * @param int $level
59
	 * @param int $circleId
60
	 *
61
	 * @return Circle[]
62
	 * @throws ConfigNoCircleAvailable
63
	 */
64
	public function findCirclesByUser($userId, $type, $name = '', $level = 0, $circleId = -1) {
65
66
		$type = (int)$type;
67
		$level = (int)$level;
68
		$circleId = (int)$circleId;
69
70
		$qb = $this->db->getQueryBuilder();
71
		$qb->select(
72
			'c.id', 'c.name', 'c.description', 'c.type', 'c.creation',
73
			'u.joined', 'u.level', 'u.status'
74
		)
75
		   ->selectAlias('o.user_id', 'owner')
76
		   ->from(self::TABLENAME, 'c')
77
		   ->from(MembersMapper::TABLENAME, 'o')
78
		   ->where(
79
			   $qb->expr()
80
				  ->eq('c.id', 'o.circle_id'),
81
			   $qb->expr()
82
				  ->eq('o.level', $qb->createNamedParameter(Member::LEVEL_OWNER))
83
		   );
84
85
86
		if ($level > 0) {
87
			$qb->andWhere(
88
				$qb->expr()
89
				   ->gte('u.level', $qb->createNamedParameter($level))
90
			);
91
		}
92
		if ($circleId > 0) {
93
			$qb->andWhere(
94
				$qb->expr()
95
				   ->eq('c.id', $qb->createNamedParameter($circleId))
96
			);
97
		}
98
99
100
		$qb->leftJoin(
101
			'c', MembersMapper::TABLENAME, 'u',
102
			$qb->expr()
103
			   ->andX(
104
				   $qb->expr()
105
					  ->eq('c.id', 'u.circle_id'),
106
				   $qb->expr()
107
					  ->eq('u.user_id', $qb->createNamedParameter($userId))
108
			   )
109
		);
110
111
		$orTypesArray = [];
112
		if (Circle::CIRCLES_PERSONAL & (int)$type) {
113
			array_push(
114
				$orTypesArray,
115
				$qb->expr()
116
				   ->andX(
117
					   $qb->expr()
118
						  ->eq('c.type', $qb->createNamedParameter(Circle::CIRCLES_PERSONAL)),
119
					   $qb->expr()
120
						  ->eq('o.user_id', $qb->createNamedParameter($userId))
121
				   )
122
			);
123
		}
124
125
		if (Circle::CIRCLES_HIDDEN & (int)$type) {
126
			array_push(
127
				$orTypesArray, $qb->expr()
128
								  ->andX(
129
									  $qb->expr()
130
										 ->eq(
131
											 'c.type',
132
											 $qb->createNamedParameter(Circle::CIRCLES_HIDDEN)
133
										 ),
134
									  $qb->expr()
135
										 ->orX(
136
											 $qb->expr()
137
												->gte(
138
													'u.level',
139
													$qb->createNamedParameter(Member::LEVEL_MEMBER)
140
												),
141
											 $qb->expr()
142
												->eq(
143
													'c.id',
144
													$qb->createNamedParameter($circleId)
145
												),
146
											 $qb->expr()
147
												->eq(
148
													'c.name',
149
													$qb->createNamedParameter($name)
150
												)
151
										 )
152
								  )
153
			);
154
		}
155 View Code Duplication
		if (Circle::CIRCLES_PRIVATE & (int)$type) {
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...
156
			array_push(
157
				$orTypesArray, $qb->expr()
158
								  ->eq(
159
									  'c.type',
160
									  $qb->createNamedParameter(Circle::CIRCLES_PRIVATE)
161
								  )
162
			);
163
		}
164 View Code Duplication
		if (Circle::CIRCLES_PUBLIC & (int)$type) {
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...
165
			array_push(
166
				$orTypesArray, $qb->expr()
167
								  ->eq(
168
									  'c.type',
169
									  $qb->createNamedParameter(Circle::CIRCLES_PUBLIC)
170
								  )
171
			);
172
		}
173
174
		if (sizeof($orTypesArray) === 0) {
175
			throw new ConfigNoCircleAvailable();
176
		}
177
178
		$orXTypes = $qb->expr()
179
					   ->orX();
180
181
		foreach ($orTypesArray as $orTypes) {
182
			$orXTypes->add($orTypes);
183
		}
184
185
		$qb->andWhere($orXTypes);
186
187
		$qb->groupBy('c.id');
188
		$qb->orderBy('c.name', 'ASC');
189
190
		$cursor = $qb->execute();
191
192
		$result = [];
193
		while ($data = $cursor->fetch()) {
194
			if ($name === '' || stripos($data['name'], $name) !== false) {
195
				$circle = new Circle();
196
				$result[] = $circle->fromArray($data);
197
			}
198
		}
199
		$cursor->closeCursor();
200
201
		return $result;
202
	}
203
204
205
	/**
206
	 * Returns details about a circle.
207
	 *
208
	 * @param string $userId
209
	 * @param int $circleId
210
	 *
211
	 * @return Circle
212
	 * @throws CircleDoesNotExistException
213
	 * @throws ConfigNoCircleAvailable
214
	 */
215
	public function getDetailsFromCircle($userId, $circleId) {
216
217
		try {
218
			$result = $this->findCirclesByUser($userId, Circle::CIRCLES_ALL, '', 0, $circleId);
219
		} catch (ConfigNoCircleAvailable $e) {
220
			throw $e;
221
		}
222
223
		if (sizeof($result) !== 1) {
224
			throw new CircleDoesNotExistException(
225
				"The circle does not exist or is hidden to the user"
226
			);
227
		}
228
229
		return $result[0];
230
	}
231
232
233
	/**
234
	 * @param Circle $circle
235
	 * @param Member $owner
236
	 *
237
	 * @return bool
238
	 * @throws CircleAlreadyExistsException
239
	 * @throws CircleCreationException
240
	 * @throws ConfigNoCircleAvailable
241
	 */
242
	public function create(Circle &$circle, Member &$owner) {
243
244
		if ($circle->getType() === Circle::CIRCLES_PERSONAL) {
245
246
			try {
247
				$list = $this->findCirclesByUser(
248
					$owner->getUserId(), Circle::CIRCLES_PERSONAL, $circle->getName(),
249
					Member::LEVEL_OWNER
250
				);
251
			} catch (ConfigNoCircleAvailable $e) {
252
				throw $e;
253
			}
254
255
			foreach ($list as $test) {
256
				if ($test->getName() === $circle->getName()) {
257
					throw new CircleAlreadyExistsException();
258
				}
259
			}
260
261
		} else {
262
263
			$qb = $this->db->getQueryBuilder();
264
			$qb->select(
265
				'c.id', 'c.name', 'c.type'
266
			)
267
			   ->from(self::TABLENAME, 'c')
268
			   ->where(
269
				   $qb->expr()
270
					  ->neq('c.type', $qb->createNamedParameter(Circle::CIRCLES_PERSONAL))
271
			   );
272
273
			$cursor = $qb->execute();
274
275
			while ($data = $cursor->fetch()) {
276
				if (strtolower($data['name']) === strtolower($circle->getName())) {
277
					throw new CircleAlreadyExistsException();
278
				}
279
			}
280
			$cursor->closeCursor();
281
282
		}
283
284
285
		$qb = $this->db->getQueryBuilder();
286
		$qb->insert(self::TABLENAME)
287
		   ->setValue('name', $qb->createNamedParameter($circle->getName()))
288
		   ->setValue('description', $qb->createNamedParameter($circle->getDescription()))
289
		   ->setValue('type', $qb->createNamedParameter($circle->getType()))
290
		   ->setValue('creation', 'CURRENT_TIMESTAMP()');
291
		$qb->execute();
292
		$circleid = $qb->getLastInsertId();
293
294
295
		if ($circleid < 1) {
296
			throw new CircleCreationException();
297
		}
298
299
		$circle->setId($circleid);
300
		$owner->setLevel(Member::LEVEL_OWNER)
301
			  ->setStatus(Member::STATUS_MEMBER)
302
			  ->setCircleId($circleid);
303
304
		return true;
305
	}
306
307
308
	/**
309
	 * remove a circle
310
	 *
311
	 * @param Circle $circle
312
	 */
313 View Code Duplication
	public function destroy(Circle $circle) {
1 ignored issue
show
Duplication introduced by
This method seems to be duplicated in 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...
314
		$qb = $this->db->getQueryBuilder();
315
		$qb->delete(self::TABLENAME)
316
		   ->where(
317
			   $qb->expr()
318
				  ->eq(
319
					  'id', $qb->createNamedParameter($circle->getId())
320
				  )
321
		   );
322
323
		$qb->execute();
324
	}
325
326
}
327
328