Passed
Pull Request — master (#966)
by René
04:17
created

PollService::update()   D

Complexity

Conditions 18
Paths 5

Size

Total Lines 36
Code Lines 22

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 342

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 18
eloc 22
c 1
b 0
f 0
nc 5
nop 2
dl 0
loc 36
ccs 0
cts 27
cp 0
crap 342
rs 4.8666

How to fix   Complexity   

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
 * @copyright Copyright (c) 2017 Vinzenz Rosenkranz <[email protected]>
4
 *
5
 * @author René Gieling <[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\Polls\Service;
25
26
 use Exception;
27
 use OCP\AppFramework\Db\DoesNotExistException;
28
 use OCA\Polls\Exceptions\EmptyTitleException;
29
 use OCA\Polls\Exceptions\InvalidAccessException;
30
 use OCA\Polls\Exceptions\InvalidShowResultsException;
31
 use OCA\Polls\Exceptions\InvalidPollTypeException;
32
 use OCA\Polls\Exceptions\NotAuthorizedException;
33
34
 use OCP\ILogger;
35
36
 use OCA\Polls\Db\Poll;
37
 use OCA\Polls\Db\PollMapper;
38
 use OCA\Polls\Service\CommentService;
39
 use OCA\Polls\Service\OptionService;
40
 use OCA\Polls\Service\ShareService;
41
 use OCA\Polls\Service\VoteService;
42
 use OCA\Polls\Service\LogService;
43
 use OCA\Polls\Model\Acl;
44
45
 class PollService {
46
47
	private $logger;
48
	private $userid;
0 ignored issues
show
introduced by
The private property $userid is not used, and could be removed.
Loading history...
49
	private $pollMapper;
50
 	private $poll;
51
 	private $logService;
52
 	private $commentService;
53
 	private $optionService;
54
 	private $shareService;
55
 	private $voteService;
56
 	private $acl;
57
58
 	/**
59
 	 * PollController constructor.
60
 	 * @param string $appName
61
 	 * @param $userId
62
 	 * @param PollMapper $pollMapper
63
 	 * @param LogService $logService
64
 	 * @param CommentService $commentService
65
 	 * @param OptionService $optionService
66
 	 * @param ShareService $shareService
67
 	 * @param VoteService $voteService
68
 	 * @param Acl $acl
69
 	 */
70
71
 	public function __construct(
72
 		string $appName,
0 ignored issues
show
Unused Code introduced by
The parameter $appName is not used and could be removed. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-unused  annotation

72
 		/** @scrutinizer ignore-unused */ string $appName,

This check looks for parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
73
		$userId,
74
		ILogger $logger,
75
 		PollMapper $pollMapper,
76
 		Poll $poll,
77
 		LogService $logService,
78
		CommentService $commentService,
79
		OptionService $optionService,
80
		ShareService $shareService,
81
		VoteService $voteService,
82
 		Acl $acl
83
 	) {
84
		$this->userId = $userId;
0 ignored issues
show
Bug Best Practice introduced by
The property userId does not exist. Although not strictly required by PHP, it is generally a best practice to declare properties explicitly.
Loading history...
85
		$this->logger = $logger;
86
 		$this->pollMapper = $pollMapper;
87
 		$this->poll = $poll;
88
 		$this->logService = $logService;
89
 		$this->commentService = $commentService;
90
 		$this->optionService = $optionService;
91
 		$this->shareService = $shareService;
92
 		$this->voteService = $voteService;
93
 		$this->acl = $acl;
94
 	}
95
96
97
	/**
98
	 * list
99
	 * @NoAdminRequired
100
	 * @return DataResponse
0 ignored issues
show
Bug introduced by
The type OCA\Polls\Service\DataResponse was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
101
	 */
102
103
	public function list() {
104
		if (!\OC::$server->getUserSession()->isLoggedIn()) {
105
			throw new NotAuthorizedException;
106
		}
107
108
		$polls = $this->pollMapper->findAll();
109
		// TODO: Not the elegant way. Improvement neccessary
110
		foreach ($polls as $poll) {
111
			$combinedPoll = (object) array_merge(
112
				(array) json_decode(json_encode($poll)), (array) json_decode(json_encode($this->acl->setPollId($poll->getId()))));
113
			if ($combinedPoll->allowView) {
114
				$pollList[] = $combinedPoll;
115
			}
116
		}
117
118
		return $pollList;
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $pollList does not seem to be defined for all execution paths leading up to this point.
Loading history...
119
	}
120
121
	/**
122
	 * get
123
	 * @NoAdminRequired
124
	 * @param integer $pollId
125
	 * @return array
126
	 */
127
 	public function get($pollId = 0, $token = '') {
128
129
		if (!$this->acl->setPollIdOrToken($pollId, $token)->getAllowView()) {
130
			throw new NotAuthorizedException;
131
		}
132
133
		$this->poll = $this->pollMapper->find($this->acl->getPollId());
134
135
		try {
136
			$comments = $this->commentService->list($this->poll->getId(), $token);
137
		} catch (Exception $e) {
138
			$comments = [];
139
		}
140
141
		try {
142
			$options = $this->optionService->list($this->poll->getId(), $token);
143
		} catch (Exception $e) {
144
			$options = [];
145
146
		}
147
148
		try {
149
			$votes = $this->voteService->list($this->poll->getId(), $token);
150
		} catch (Exception $e) {
151
			$votes = [];
152
		}
153
154
		try {
155
			$shares = $this->shareService->list($this->poll->getId());
156
		} catch (Exception $e) {
157
			$shares = [];
158
		}
159
160
		return [
161
			'acl' => $this->acl,
162
			'poll' => $this->poll,
163
			'comments' => $comments,
164
			'options' => $options,
165
			'shares' => $shares,
166
			'votes' => $votes
167
		];
168
 	}
169
170
	/**
171
	 * delete
172
	 * @NoAdminRequired
173
	 * @NoCSRFRequired
174
	 * @param integer $pollId
175
	 * @return Poll
176
	 */
177
178
	public function delete($pollId) {
179
		$this->poll = $this->pollMapper->find($pollId);
180
181
		if (!$this->acl->setPollId($pollId)->getAllowEdit()) {
182
			throw new NotAuthorizedException;
183
		}
184
185
		if ($this->poll->getDeleted()) {
186
			$this->poll->setDeleted(0);
187
		} else {
188
			$this->poll->setDeleted(time());
189
		}
190
191
		$this->poll = $this->pollMapper->update($this->poll);
192
		$this->logService->setLog($this->poll->getId(), 'deletePoll');
193
194
		return $this->poll;
195
	}
196
197
	/**
198
	 * deletePermanently
199
	 * @NoAdminRequired
200
	 * @NoCSRFRequired
201
	 * @param integer $pollId
202
	 * @return Poll
203
	 */
204
205
	public function deletePermanently($pollId) {
206
		$this->poll = $this->pollMapper->find($pollId);
207
208
		if (!$this->acl->setPollId($pollId)->getAllowEdit() || !$this->poll->getDeleted()) {
209
			throw new NotAuthorizedException;
210
		}
211
212
		return $this->pollMapper->delete($this->poll);
213
	}
214
215
	/**
216
	 * write
217
	 * @NoAdminRequired
218
	 * @NoCSRFRequired
219
	 * @param Array $poll
220
	 * @return DataResponse
221
	 */
222
223
	public function add($type, $title) {
224
		if (!\OC::$server->getUserSession()->isLoggedIn()) {
225
			throw new NotAuthorizedException;
226
		}
227
228
		// Validate valuess
229
		if (!in_array($type, $this->getValidPollType())) {
230
			throw new InvalidPollTypeException('Invalid poll type');
231
		}
232
233
		if (!$title) {
234
			throw new EmptyTitleException('Title must not be empty');
235
		}
236
237
		$this->poll = new Poll();
238
		$this->poll->setType($type);
239
		$this->poll->setCreated(time());
240
		$this->poll->setOwner($this->userId);
241
		$this->poll->setTitle($title);
242
		$this->poll->setDescription('');
243
		$this->poll->setAccess('hidden');
244
		$this->poll->setExpire(0);
245
		$this->poll->setAnonymous(0);
246
		$this->poll->setFullAnonymous(0);
247
		$this->poll->setAllowMaybe(0);
248
		$this->poll->setVoteLimit(0);
249
		$this->poll->setSettings('');
250
		$this->poll->setOptions('');
251
		$this->poll->setShowResults('always');
252
		$this->poll->setDeleted(0);
253
		$this->poll->setAdminAccess(0);
254
		$this->poll = $this->pollMapper->insert($this->poll);
255
256
		$this->logService->setLog($this->poll->getId(), 'addPoll');
257
258
		return $this->poll;
259
	}
260
261
	// /**
262
	//  * write
263
	//  * @NoAdminRequired
264
	//  * @NoCSRFRequired
265
	//  * @depricated
266
	//  * @param Array $poll
267
	//  * @return DataResponse
268
	//  */
269
	//
270
	// public function write($poll, $pollId = null) {
271
	//
272
	// 	if (!$pollId) {
273
	// 		$pollId = $poll['id'];
274
	// 	}
275
	//
276
	// 	// Validate valuess
277
	// 	if (isset($poll['showResults']) && !in_array($poll['showResults'], $this->getValidShowResults())) {
278
	// 		throw new InvalidShowResultsException('Invalid value for prop showResults');
279
	// 	}
280
	//
281
	// 	if (isset($poll['access']) && !in_array($poll['access'], $this->getValidShowResults())) {
282
	// 		throw new InvalidAccessException('Invalid value for prop access');
283
	// 	}
284
	//
285
	// 	if (isset($poll['title']) && !$poll['title']) {
286
	// 		throw new EmptyTitleException('Title must not be empty');
287
	// 	}
288
	//
289
	// 	try {
290
	// 		// find pollId
291
	// 		$this->poll = $this->pollMapper->find($pollId);
292
	// 		$this->logService->setLog($this->poll->getId(), 'updatePoll');
293
	//
294
	//
295
	// 	} catch (DoesNotExistException $e) {
296
	// 		// if not found create a new poll
297
	//
298
	// 		// Validate valuess
299
	// 		if (!in_array($poll['type'], $this->getValidPollType())) {
300
	// 			throw new InvalidPollTypeException('Invalid poll type');
301
	// 		}
302
	//
303
	// 		if (!$poll['title']) {
304
	// 			throw new EmptyTitleException('Title must not be empty');
305
	// 		}
306
	//
307
	//
308
	// 		$this->poll = new Poll();
309
	// 		$this->poll->setType($poll['type']);
310
	// 		$this->poll->setOwner($this->userId);
311
	// 		$this->poll->setTitle($poll['title']);
312
	// 		$this->poll->setCreated(time());
313
	// 		$this->poll = $this->pollMapper->insert($this->poll);
314
	//
315
	// 		$this->logService->setLog($this->poll->getId(), 'addPoll');
316
	// 	}
317
	//
318
	// 	if (!$this->acl->setPollId($this->poll->getId())->getAllowEdit()) {
319
	// 		throw new NotAuthorizedException;
320
	// 	}
321
	//
322
	// 	$this->poll->setTitle(isset($poll['title']) ? $poll['title'] : $this->poll->getTitle());
323
	// 	$this->poll->setDescription(isset($poll['description']) ? $poll['description'] : $this->poll->getDescription());
324
	// 	$this->poll->setAccess(isset($poll['access']) ? $poll['access'] : $this->poll->getAccess());
325
	// 	$this->poll->setExpire(isset($poll['expire']) ? $poll['expire'] : $this->poll->getExpire());
326
	// 	$this->poll->setAnonymous(isset($poll['anonymous']) ? $poll['anonymous'] : $this->poll->getAnonymous());
327
	// 	$this->poll->setAllowMaybe(isset($poll['allowMaybe']) ? $poll['allowMaybe'] : $this->poll->getAllowMaybe());
328
	// 	$this->poll->setVoteLimit(isset($poll['voteLimit']) ? $poll['voteLimit'] : $this->poll->getVoteLimit());
329
	// 	$this->poll->setShowResults(isset($poll['showResults']) ? $poll['showResults'] : $this->poll->getShowResults());
330
	// 	$this->poll->setDeleted(isset($poll['deleted']) ? $poll['deleted'] : $this->poll->getDeleted());
331
	// 	$this->poll->setAdminAccess(isset($poll['adminAccess']) ? $poll['adminAccess'] : $this->poll->getAdminAccess());
332
	//
333
	// 	$this->poll->setFullAnonymous(0);
334
	// 	$this->poll->setVoteLimit(0);
335
	// 	$this->poll->setSettings('');
336
	// 	$this->poll->setOptions('');
337
	//
338
	// 	$this->pollMapper->update($this->poll);
339
	//
340
	// 	return $this->poll;
341
	// }
342
343
	/**
344
	 * update
345
	 * @NoAdminRequired
346
	 * @NoCSRFRequired
347
	 * @param Array $poll
348
	 * @return DataResponse
349
	 */
350
351
	public function update($pollId, $poll) {
352
353
		$this->poll = $this->pollMapper->find($pollId);
354
355
		if (!$this->acl->setPollId($this->poll->getId())->getAllowEdit()) {
356
			throw new NotAuthorizedException;
357
		}
358
359
		// Validate valuess
360
		if (isset($poll['showResults']) && !in_array($poll['showResults'], $this->getValidShowResults())) {
361
			throw new InvalidShowResultsException('Invalid value for prop showResults');
362
		}
363
364
		if (isset($poll['access']) && !in_array($poll['access'], $this->getValidAccess())) {
365
			throw new InvalidAccessException('Invalid value for prop access '. $poll['access']);
366
		}
367
368
		if (isset($poll['title']) && !$poll['title']) {
369
			throw new EmptyTitleException('Title must not be empty');
370
		}
371
372
		$this->poll->setTitle($poll['title'] ? $poll['title'] : $this->poll->getTitle());
373
		$this->poll->setDescription(isset($poll['description']) ? $poll['description'] : $this->poll->getDescription());
374
		$this->poll->setAccess(isset($poll['access']) ? $poll['access'] : $this->poll->getAccess());
375
		$this->poll->setExpire(isset($poll['expire']) ? $poll['expire'] : $this->poll->getExpire());
376
		$this->poll->setAnonymous(isset($poll['anonymous']) ? $poll['anonymous'] : $this->poll->getAnonymous());
377
		$this->poll->setAllowMaybe(isset($poll['allowMaybe']) ? $poll['allowMaybe'] : $this->poll->getAllowMaybe());
378
		$this->poll->setVoteLimit(isset($poll['voteLimit']) ? $poll['voteLimit'] : $this->poll->getVoteLimit());
379
		$this->poll->setShowResults(isset($poll['showResults']) ? $poll['showResults'] : $this->poll->getShowResults());
380
		$this->poll->setDeleted(isset($poll['deleted']) ? $poll['deleted'] : $this->poll->getDeleted());
381
		$this->poll->setAdminAccess(isset($poll['adminAccess']) ? $poll['adminAccess'] : $this->poll->getAdminAccess());
382
383
		$this->pollMapper->update($this->poll);
384
		$this->logService->setLog($this->poll->getId(), 'updatePoll');
385
386
		return $this->poll;
387
	}
388
389
	/**
390
	 * clone
391
	 * @NoAdminRequired
392
	 * @NoCSRFRequired
393
	 * @param integer $pollId
394
	 * @return DataResponse
395
	 */
396
	public function clone($pollId) {
397
398
		if (!$this->acl->setPollId($this->poll->getId())->getAllowView()) {
399
			throw new NotAuthorizedException;
400
		}
401
402
		$this->poll = $this->pollMapper->find($pollId);
403
404
		$this->poll->setCreated(time());
405
		$this->poll->setOwner($this->userId);
406
		$this->poll->setTitle('Clone of ' . $this->poll->getTitle());
407
		$this->poll->setDeleted(0);
408
		$this->poll->setId(0);
409
410
		$this->poll = $this->pollMapper->insert($this->poll);
411
		$this->logService->setLog($clonePoll->getId(), 'addPoll');
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $clonePoll seems to be never defined.
Loading history...
412
413
		$this->optionService->clone($pollId, $this->poll->getId());
414
415
		return $this->poll;
416
417
	}
418
419
	public function getValidEnum() {
420
		return [
421
			'pollType' => $this->getValidPollType(),
422
			'access' => $this->getValidAccess(),
423
			'showResults' => $this->getValidShowResults()
424
		];
425
	}
426
427
	private function getValidPollType() {
428
		return ['datePoll', 'textPoll'];
429
	}
430
431
	private function getValidAccess() {
432
		return ['hidden', 'public'];
433
	}
434
435
	private function getValidShowResults() {
436
		return ['always', 'expired', 'never'];
437
	}
438
}
439