Passed
Pull Request — master (#1449)
by René
05:35
created

OptionService::getUsersVotes()   A

Complexity

Conditions 3
Paths 1

Size

Total Lines 16
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 12

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 7
c 1
b 0
f 0
dl 0
loc 16
ccs 0
cts 9
cp 0
rs 10
cc 3
nc 1
nop 0
crap 12
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 DateTime;
27
use OCP\AppFramework\Db\DoesNotExistException;
28
use OCA\Polls\Exceptions\NotAuthorizedException;
29
use OCA\Polls\Exceptions\BadRequestException;
30
use OCA\Polls\Exceptions\DuplicateEntryException;
31
use Doctrine\DBAL\Exception\UniqueConstraintViolationException;
32
33
use OCA\Polls\Db\OptionMapper;
34
use OCA\Polls\Db\VoteMapper;
35
use OCA\Polls\Db\Vote;
36
use OCA\Polls\Db\Option;
37
use OCA\Polls\Db\PollMapper;
38
use OCA\Polls\Db\Poll;
39
use OCA\Polls\Db\Watch;
40
use OCA\Polls\Model\Acl;
41
42
class OptionService {
43
44
	/** @var Acl */
45
	private $acl;
46
47
	/** @var Option */
48
	private $option;
49
50
	/** @var int */
51
	private $countParticipants;
52
53
	/** @var Poll */
54
	private $poll;
55
56
	/** @var Option[] */
57
	private $options;
58
59
	/** @var Vote[] */
60
	private $votes;
61
62
	/** @var OptionMapper */
63
	private $optionMapper;
64
65
	/** @var PollMapper */
66
	private $pollMapper;
67
68
	/** @var VoteMapper */
69
	private $voteMapper;
70
71
	/** @var WatchService */
72
	private $watchService;
73
74
	public function __construct(
75
		Acl $acl,
76
		Option $option,
77
		OptionMapper $optionMapper,
78
		PollMapper $pollMapper,
79
		VoteMapper $voteMapper,
80
		WatchService $watchService
81
	) {
82
		$this->acl = $acl;
83
		$this->option = $option;
84
		$this->optionMapper = $optionMapper;
85
		$this->pollMapper = $pollMapper;
86
		$this->voteMapper = $voteMapper;
87
		$this->watchService = $watchService;
88
	}
89
90
	/**
91
	 * 	 * Get all options of given poll
92
	 *
93
	 * @return Option[]
94
	 *
95
	 * @psalm-return array<array-key, Option>
96
	 */
97
	public function list(int $pollId = 0, string $token = ''): array {
98
		if ($token) {
99
			$this->acl->setToken($token);
100
			$pollId = $this->acl->getPollId();
101
		} else {
102
			$this->acl->setPollId($pollId)->request(Acl::PERMISSION_VIEW);
103
		}
104
105
		if (!$this->acl->isAllowed(Acl::PERMISSION_VIEW)) {
106
			throw new NotAuthorizedException;
107
		}
108
109
		try {
110
			$this->poll = $this->pollMapper->find($pollId);
111
			$this->options = $this->optionMapper->findByPoll($pollId);
112
			$this->votes = $this->voteMapper->findByPoll($pollId);
113
			$this->countParticipants = count($this->voteMapper->findParticipantsByPoll($pollId));
114
115
			$this->calculateVotes();
116
117
			if ($this->poll->getHideBookedUp() && !$this->acl->isAllowed(Acl::PERMISSION_EDIT)) {
118
				// hide booked up options except the user has edit permission
119
				$this->filterBookedUp();
120
			} elseif ($this->acl->isAllowed(Acl::PERMISSION_SEE_RESULTS)) {
121
				$this->calculateRanks();
122
			}
123
124
			return array_values($this->options);
125
		} catch (DoesNotExistException $e) {
126
			return [];
127
		}
128
	}
129
130
	/**
131
	 * 	 * Get option
132
	 *
133
	 * @return Option
134
	 */
135
	public function get(int $optionId): Option {
136
		$this->acl->setPollId($this->optionMapper->find($optionId)->getPollId())->request(Acl::PERMISSION_VIEW);
137
		$this->acl->request(Acl::PERMISSION_VIEW);
138
139
		return $this->optionMapper->find($optionId);
140
	}
141
142
143
	/**
144
	 * 	 * Add a new option
145
	 *
146
	 * @return Option
147
	 */
148
	public function add(int $pollId, int $timestamp = 0, string $pollOptionText = '', ?int $duration = 0): Option {
149
		$this->acl->setPollId($pollId)->request(Acl::PERMISSION_EDIT);
150
		$this->option = new Option();
151
		$this->option->setPollId($pollId);
152
		$this->option->setOrder($this->getHighestOrder($this->option->getPollId()) + 1);
153
		$this->setOption($timestamp, $pollOptionText, $duration);
154
155
		try {
156
			$this->option = $this->optionMapper->insert($this->option);
157
			$this->watchService->writeUpdate($this->option->getPollId(), Watch::OBJECT_OPTIONS);
158
		} catch (UniqueConstraintViolationException $e) {
159
			throw new DuplicateEntryException('This option already exists');
160
		}
161
		return $this->option;
162
	}
163
164
	/**
165
	 * 	 * Update option
166
	 *
167
	 * @return Option
168
	 */
169
	public function update(int $optionId, int $timestamp = 0, ?string $pollOptionText = '', ?int $duration = 0): Option {
170
		$this->option = $this->optionMapper->find($optionId);
171
		$this->acl->setPollId($this->option->getPollId())->request(Acl::PERMISSION_EDIT);
172
		$this->setOption($timestamp, $pollOptionText, $duration);
173
174
		$this->option = $this->optionMapper->update($this->option);
175
		$this->watchService->writeUpdate($this->option->getPollId(), Watch::OBJECT_OPTIONS);
176
		return $this->option;
177
	}
178
179
	/**
180
	 * 	 * Delete option
181
	 *
182
	 * @return Option
183
	 */
184
	public function delete(int $optionId): Option {
185
		$this->option = $this->optionMapper->find($optionId);
186
		$this->acl->setPollId($this->option->getPollId())->request(Acl::PERMISSION_EDIT);
187
		$this->optionMapper->delete($this->option);
188
		$this->watchService->writeUpdate($this->option->getPollId(), Watch::OBJECT_OPTIONS);
189
190
		return $this->option;
191
	}
192
193
	/**
194
	 * 	 * Switch optoin confirmation
195
	 *
196
	 * @return Option
197
	 */
198
	public function confirm(int $optionId): Option {
199
		$this->option = $this->optionMapper->find($optionId);
200
		$this->acl->setPollId($this->option->getPollId())->request(Acl::PERMISSION_EDIT);
201
202
		$this->option->setConfirmed($this->option->getConfirmed() ? 0 : time());
203
		$this->option = $this->optionMapper->update($this->option);
204
		$this->watchService->writeUpdate($this->option->getPollId(), Watch::OBJECT_OPTIONS);
205
		return $this->option;
206
	}
207
208
	/**
209
	 * 	 * Make a sequence of date poll options
210
	 * @param int $optionId
211
	 * @param int $step - The step for creating the sequence
212
	 * @param string $unit - The timeunit (year, month, ...)
213
	 * @param int $amount - Number of sequence items to create
214
	 *
215
	 * @return Option[]
216
	 *
217
	 * @psalm-return array<array-key, Option>
218
	 */
219
	public function sequence(int $optionId, int $step, string $unit, int $amount): array {
220
		$baseDate = new DateTime;
221
		$this->option = $this->optionMapper->find($optionId);
222
		$this->acl->setPollId($this->option->getPollId())->request(Acl::PERMISSION_EDIT);
223
224
		if ($step === 0) {
225
			return $this->optionMapper->findByPoll($this->option->getPollId());
226
		}
227
228
		$baseDate->setTimestamp($this->option->getTimestamp());
229
230
		for ($i = 0; $i < $amount; $i++) {
231
			$clonedOption = new Option();
232
			$clonedOption->setPollId($this->option->getPollId());
233
			$clonedOption->setDuration($this->option->getDuration());
234
			$clonedOption->setConfirmed(0);
235
			$clonedOption->setTimestamp($baseDate->modify($step . ' ' . $unit)->getTimestamp());
236
			$clonedOption->setOrder($clonedOption->getTimestamp());
237
			$clonedOption->setPollOptionText($baseDate->format('c'));
238
			try {
239
				$this->optionMapper->insert($clonedOption);
240
			} catch (UniqueConstraintViolationException $e) {
241
				\OC::$server->getLogger()->warning('skip adding ' . $baseDate->format('c') . 'for pollId' . $this->option->getPollId() . '. Option alredy exists.');
242
			}
243
		}
244
		$this->watchService->writeUpdate($this->option->getPollId(), Watch::OBJECT_OPTIONS);
245
		return $this->optionMapper->findByPoll($this->option->getPollId());
246
	}
247
248
	/**
249
	 * 	 * Copy options from $fromPoll to $toPoll
250
	 *
251
	 * @return Option[]
252
	 *
253
	 * @psalm-return array<array-key, Option>
254
	 */
255
	public function clone(int $fromPollId, int $toPollId): array {
256
		$this->acl->setPollId($fromPollId);
257
258
		foreach ($this->optionMapper->findByPoll($fromPollId) as $origin) {
259
			$option = new Option();
260
			$option->setPollId($toPollId);
261
			$option->setConfirmed(0);
262
			$option->setPollOptionText($origin->getPollOptionText());
263
			$option->setTimestamp($origin->getTimestamp());
264
			$option->setDuration($origin->getDuration());
265
			$option->setOrder($option->getOrder());
266
			$this->optionMapper->insert($option);
267
		}
268
269
		return $this->optionMapper->findByPoll($toPollId);
270
	}
271
272
	/**
273
	 * Reorder options with the order specified by $options
274
	 *
275
	 * @return Option[]
276
	 *
277
	 * @psalm-return array<array-key, Option>
278
	 */
279
	public function reorder(int $pollId, array $options): array {
280
		try {
281
			$this->poll = $this->pollMapper->find($pollId);
282
			$this->acl->setPoll($this->poll)->request(Acl::PERMISSION_EDIT);
283
284
			if ($this->poll->getType() === Poll::TYPE_DATE) {
285
				throw new BadRequestException("Not allowed in date polls");
286
			}
287
		} catch (DoesNotExistException $e) {
288
			throw new NotAuthorizedException;
289
		}
290
291
		$i = 0;
292
		foreach ($options as $option) {
293
			$this->option = $this->optionMapper->find($option['id']);
294
			if ($pollId === intval($this->option->getPollId())) {
295
				$this->option->setOrder(++$i);
296
				$this->optionMapper->update($this->option);
297
			}
298
		}
299
300
		$this->watchService->writeUpdate($pollId, Watch::OBJECT_OPTIONS);
301
		return $this->optionMapper->findByPoll($pollId);
302
	}
303
304
	/**
305
	 * Change order for $optionId and reorder the options
306
	 *
307
	 * @return Option[]
308
	 *
309
	 * @psalm-return array<array-key, Option>
310
	 */
311
	public function setOrder(int $optionId, int $newOrder): array {
312
		try {
313
			$this->option = $this->optionMapper->find($optionId);
314
			$this->poll = $this->pollMapper->find($this->option->getPollId());
315
			$this->acl->setPoll($this->poll)->request(Acl::PERMISSION_EDIT);
316
317
			if ($this->poll->getType() === Poll::TYPE_DATE) {
318
				throw new BadRequestException("Not allowed in date polls");
319
			}
320
		} catch (DoesNotExistException $e) {
321
			throw new NotAuthorizedException;
322
		}
323
324
		if ($newOrder < 1) {
325
			$newOrder = 1;
326
		} elseif ($newOrder > $this->getHighestOrder($this->poll->getId())) {
327
			$newOrder = $this->getHighestOrder($this->poll->getId());
328
		}
329
330
		foreach ($this->optionMapper->findByPoll($this->poll->getId()) as $option) {
331
			$option->setOrder($this->moveModifier($this->option->getOrder(), $newOrder, $option->getOrder()));
332
			$this->optionMapper->update($option);
333
		}
334
335
		$this->watchService->writeUpdate($this->option->getPollId(), Watch::OBJECT_OPTIONS);
336
		return $this->optionMapper->findByPoll($this->option->getPollId());
337
	}
338
339
	/**
340
	 * moveModifier - evaluate new order depending on the old and
341
	 * the new position of a moved array item
342
	 * @param int $moveFrom - old position of the moved item
343
	 * @param int $moveTo - target posotion of the moved item
344
	 * @param int $currentPosition - current position of the current item
345
	 *
346
	 * @return int - The modified new new position of the current item
347
	 */
348
	private function moveModifier(int $moveFrom, int $moveTo, int $currentPosition): int {
349
		$moveModifier = 0;
350
		if ($moveFrom < $currentPosition && $currentPosition <= $moveTo) {
351
			// moving forward
352
			$moveModifier = -1;
353
		} elseif ($moveTo <= $currentPosition && $currentPosition < $moveFrom) {
354
			//moving backwards
355
			$moveModifier = 1;
356
		} elseif ($moveFrom === $currentPosition) {
357
			return $moveTo;
358
		}
359
		return $currentPosition + $moveModifier;
360
	}
361
362
	/**
363
	 * Set option entities validated
364
	 *
365
	 * @return void
366
	 */
367
	private function setOption(int $timestamp = 0, ?string $pollOptionText = '', ?int $duration = 0): void {
368
		$this->poll = $this->pollMapper->find($this->option->getPollId());
369
370
		if ($this->poll->getType() === Poll::TYPE_DATE) {
371
			$this->option->setTimestamp($timestamp);
372
			$this->option->setOrder($timestamp);
373
			$this->option->setDuration($duration);
374
			if ($duration === 0) {
375
				$this->option->setPollOptionText(date('c', $timestamp));
376
			} elseif ($duration > 0) {
377
				$this->option->setPollOptionText(date('c', $timestamp) . ' - ' . date('c', $timestamp + $duration));
378
			} else {
379
				$this->option->setPollOptionText($pollOptionText);
380
			}
381
		} else {
382
			$this->option->setPollOptionText($pollOptionText);
383
		}
384
	}
385
386
	/**
387
	 * Get all voteOptionTexts of the options, the user opted in
388
	 * with yes or maybe
389
	 *
390
	 * @return array
391
	 */
392
	private function getUsersVotes() {
393
		// Thats an ugly solution, but for now, it seems to work
394
		// Optimization proposals are welcome
395
396
		// First: Find votes, where the user voted yes or maybe
397
		$userId = $this->acl->getUserId();
398
		$exceptVotes = array_filter($this->votes, function ($vote) use ($userId) {
399
			if ($vote->getUserId() === $userId && in_array($vote->getVoteAnswer(), ['yes', 'maybe'])) {
400
				return $vote;
401
			}
402
		});
403
404
		// Second: Extract only the vote option texts to an array
405
		return array_values(array_map(function ($vote) {
406
			return $vote->getVoteOptionText();
407
		}, $exceptVotes));
408
	}
409
410
	/**
411
	 * Remove booked up options, because they are not votable
412
	 *
413
	 * @return void
414
	 */
415
	private function filterBookedUp() {
416
		$exceptVotes = $this->getUsersVotes();
417
		$this->options = array_filter($this->options, function ($option) use ($exceptVotes) {
418
			return (!$option->getIsBookedUp() || in_array($option->getPollOptionText(), $exceptVotes));
419
		});
420
	}
421
422
	/**
423
	 * Calculate the votes of each option and determines if the option is booked up
424
	 * - unvoted counts as no
425
	 * - realNo reports the actually opted out votes
426
	 *
427
	 * @return void
428
	 */
429
	private function calculateVotes() {
430
		foreach ($this->options as $option) {
431
			$option->yes = count(
432
				array_filter($this->votes, function ($vote) use ($option) {
433
					return ($vote->getVoteOptionText() === $option->getPollOptionText()
434
						&& $vote->getVoteAnswer() === 'yes') ;
435
				})
436
			);
437
438
			$option->realNo = count(
439
				array_filter($this->votes, function ($vote) use ($option) {
440
					return ($vote->getVoteOptionText() === $option->getPollOptionText()
441
						&& $vote->getVoteAnswer() === 'no');
442
				})
443
			);
444
445
			$option->maybe = count(
446
				array_filter($this->votes, function ($vote) use ($option) {
447
					return ($vote->getVoteOptionText() === $option->getPollOptionText()
448
						&& $vote->getVoteAnswer() === 'maybe');
449
				})
450
			);
451
452
			$option->isBookedUp = $this->poll->getOptionLimit() ? $this->poll->getOptionLimit() <= $option->yes : false;
453
454
			if (!$this->acl->isAllowed(Acl::PERMISSION_SEE_RESULTS)) {
455
				$option->yes = 0;
456
				$option->no = 0;
457
				$option->maybe = 0;
458
				$option->realNo = 0;
459
			} else {
460
				$option->no = $this->countParticipants - $option->maybe - $option->yes;
461
			}
462
		}
463
	}
464
465
	/**
466
	 * Calculate the rank of each option based on the
467
	 * yes and maybe votes and recognize equal ranked options
468
	 *
469
	 * @return void
470
	 */
471
	private function calculateRanks() {
472
		// sort array by yes and maybe votes
473
		usort($this->options, function ($a, $b) {
474
			$diff = $b->yes - $a->yes;
475
			return ($diff !== 0) ? $diff : $b->maybe - $a->maybe;
476
		});
477
478
		// calculate the rank
479
		$count = count($this->options);
480
		for ($i = 0; $i < $count; $i++) {
481
			if ($i > 0 && $this->options[$i]->yes === $this->options[$i - 1]->yes && $this->options[$i]->maybe === $this->options[$i - 1]->maybe) {
482
				$this->options[$i]->rank = $this->options[$i - 1]->rank;
483
			} else {
484
				$this->options[$i]->rank = $i + 1;
485
			}
486
		}
487
488
		// restore original order
489
		usort($this->options, function ($a, $b) {
490
			return $a->getOrder() - $b->getOrder();
491
		});
492
	}
493
494
	/**
495
	 * 	 * Get the highest order number in $pollId
496
	 * 	 * Return Highest order number
497
	 *
498
	 * @return int
499
	 */
500
	private function getHighestOrder(int $pollId): int {
501
		$highestOrder = 0;
502
		foreach ($this->optionMapper->findByPoll($pollId) as $option) {
503
			$highestOrder = ($option->getOrder() > $highestOrder) ? $option->getOrder() : $highestOrder;
504
		}
505
		return $highestOrder;
506
	}
507
}
508