Passed
Pull Request — master (#1365)
by René
03:53
created

OptionService::clone()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 15
Code Lines 12

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 6

Importance

Changes 0
Metric Value
eloc 12
c 0
b 0
f 0
dl 0
loc 15
rs 9.8666
ccs 0
cts 11
cp 0
cc 2
nc 2
nop 2
crap 6
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\Option;
35
use OCA\Polls\Db\PollMapper;
36
use OCA\Polls\Db\Poll;
37
use OCA\Polls\Db\Watch;
38
use OCA\Polls\Model\Acl;
39
40
class OptionService {
41
42
	/** @var Acl */
43
	private $acl;
44
45
	/** @var Option */
46
	private $option;
47
48
	/** @var OptionMapper */
49
	private $optionMapper;
50
51
	/** @var PollMapper */
52
	private $pollMapper;
53
54
	/** @var WatchService */
55
	private $watchService;
56
57
	public function __construct(
58
		Acl $acl,
59
		Option $option,
60
		OptionMapper $optionMapper,
61
		PollMapper $pollMapper,
62
		WatchService $watchService
63
	) {
64
		$this->acl = $acl;
65
		$this->option = $option;
66
		$this->optionMapper = $optionMapper;
67
		$this->pollMapper = $pollMapper;
68
		$this->watchService = $watchService;
69
	}
70
71
	/**
72
	 * 	 * Get all options of given poll
73
	 *
74
	 * @return Option[]
75
	 *
76
	 * @psalm-return array<array-key, Option>
77
	 */
78
	public function list(?int $pollId = 0, string $token = ''): array {
79
		if ($token) {
80
			$this->acl->setToken($token);
81
		} else {
82
			$this->acl->setPollId($pollId)->request(Acl::PERMISSION_VIEW);
83
		}
84
85
		if (!$this->acl->isAllowed(Acl::PERMISSION_VIEW)) {
86
			throw new NotAuthorizedException;
87
		}
88
89
		try {
90
			return $this->optionMapper->findByPoll($this->acl->getPollId());
91
		} catch (DoesNotExistException $e) {
92
			return [];
93
		}
94
	}
95
96
	/**
97
	 * 	 * Get option
98
	 *
99
	 * @return Option
100
	 */
101
	public function get(int $optionId): Option {
102
		$this->acl->setPollId($this->optionMapper->find($optionId)->getPollId())->request(Acl::PERMISSION_VIEW);
103
104
		if (!$this->acl->isAllowed(Acl::PERMISSION_VIEW)) {
105
			throw new NotAuthorizedException;
106
		}
107
108
		return $this->optionMapper->find($optionId);
109
	}
110
111
112
	/**
113
	 * 	 * Add a new option
114
	 *
115
	 * @return Option
116
	 */
117
	public function add(int $pollId, int $timestamp = 0, string $pollOptionText = '', ?int $duration = 0): Option {
118
		$this->acl->setPollId($pollId)->request(Acl::PERMISSION_EDIT);
119
		$this->option = new Option();
120
		$this->option->setPollId($pollId);
121
		$this->option->setOrder($this->getHighestOrder($this->option->getPollId()) + 1);
122
		$this->setOption($timestamp, $pollOptionText, $duration);
123
124
		try {
125
			$this->option = $this->optionMapper->insert($this->option);
126
			$this->watchService->writeUpdate($this->option->getPollId(), Watch::OBJECT_OPTIONS);
127
		} catch (UniqueConstraintViolationException $e) {
128
			throw new DuplicateEntryException('This option already exists');
129
		}
130
		return $this->option;
131
	}
132
133
	/**
134
	 * 	 * Update option
135
	 *
136
	 * @return Option
137
	 */
138
	public function update(int $optionId, int $timestamp = 0, ?string $pollOptionText = '', ?int $duration = 0): Option {
139
		$this->option = $this->optionMapper->find($optionId);
140
		$this->acl->setPollId($this->option->getPollId())->request(Acl::PERMISSION_EDIT);
141
		$this->setOption($timestamp, $pollOptionText, $duration);
142
143
		$this->option = $this->optionMapper->update($this->option);
144
		$this->watchService->writeUpdate($this->option->getPollId(), Watch::OBJECT_OPTIONS);
145
		return $this->option;
146
	}
147
148
	/**
149
	 * 	 * Delete option
150
	 *
151
	 * @return Option
152
	 */
153
	public function delete(int $optionId): Option {
154
		$this->option = $this->optionMapper->find($optionId);
155
		$this->acl->setPollId($this->option->getPollId())->request(Acl::PERMISSION_EDIT);
156
		$this->optionMapper->delete($this->option);
157
		$this->watchService->writeUpdate($this->option->getPollId(), Watch::OBJECT_OPTIONS);
158
159
		return $this->option;
160
	}
161
162
	/**
163
	 * 	 * Switch optoin confirmation
164
	 *
165
	 * @return Option
166
	 */
167
	public function confirm(int $optionId): Option {
168
		$this->option = $this->optionMapper->find($optionId);
169
		$this->acl->setPollId($this->option->getPollId())->request(Acl::PERMISSION_EDIT);
170
171
		if ($this->option->getConfirmed()) {
172
			$this->option->setConfirmed(0);
173
		} else {
174
			$this->option->setConfirmed(time());
175
		}
176
177
		$this->option = $this->optionMapper->update($this->option);
178
		$this->watchService->writeUpdate($this->option->getPollId(), Watch::OBJECT_OPTIONS);
179
		return $this->option;
180
	}
181
182
	/**
183
	 * 	 * Make a sequence of date poll options
184
	 *
185
	 * @return Option[]
186
	 *
187
	 * @psalm-return array<array-key, Option>
188
	 */
189
	public function sequence(int $optionId, int $step, string $unit, int $amount): array {
190
		$baseDate = new DateTime;
191
		$this->option = $this->optionMapper->find($optionId);
192
		$this->acl->setPollId($this->option->getPollId())->request(Acl::PERMISSION_EDIT);
193
194
		if ($step === 0) {
195
			return $this->optionMapper->findByPoll($this->option->getPollId());
196
		}
197
198
		$baseDate->setTimestamp($this->option->getTimestamp());
199
200
		for ($i = 0; $i < $amount; $i++) {
201
			$clonedOption = new Option();
202
			$clonedOption->setPollId($this->option->getPollId());
203
			$clonedOption->setDuration($this->option->getDuration());
204
			$clonedOption->setConfirmed(0);
205
			$clonedOption->setTimestamp($baseDate->modify($step . ' ' . $unit)->getTimestamp());
206
			$clonedOption->setOrder($clonedOption->getTimestamp());
207
			$clonedOption->setPollOptionText($baseDate->format('c'));
208
			try {
209
				$this->optionMapper->insert($clonedOption);
210
			} catch (UniqueConstraintViolationException $e) {
211
				\OC::$server->getLogger()->warning('skip adding ' . $baseDate->format('c') . 'for pollId' . $this->option->getPollId() . '. Option alredy exists.');
212
			}
213
		}
214
		$this->watchService->writeUpdate($this->option->getPollId(), Watch::OBJECT_OPTIONS);
215
		return $this->optionMapper->findByPoll($this->option->getPollId());
216
	}
217
218
	/**
219
	 * 	 * Copy options from $fromPoll to $toPoll
220
	 *
221
	 * @return Option[]
222
	 *
223
	 * @psalm-return array<array-key, Option>
224
	 */
225
	public function clone(int $fromPollId, int $toPollId): array {
226
		$this->acl->setPollId($fromPollId);
227
228
		foreach ($this->optionMapper->findByPoll($fromPollId) as $origin) {
229
			$option = new Option();
230
			$option->setPollId($toPollId);
231
			$option->setConfirmed(0);
232
			$option->setPollOptionText($origin->getPollOptionText());
233
			$option->setTimestamp($origin->getTimestamp());
234
			$option->setDuration($origin->getDuration());
235
			$option->setOrder($option->getOrder());
236
			$this->optionMapper->insert($option);
237
		}
238
239
		return $this->optionMapper->findByPoll($toPollId);
240
	}
241
242
	/**
243
	 * 	 * Reorder options with the order specified by $options
244
	 *
245
	 * @return Option[]
246
	 *
247
	 * @psalm-return array<array-key, Option>
248
	 */
249
	public function reorder(int $pollId, array $options): array {
250
		try {
251
			$poll = $this->pollMapper->find($pollId);
252
			$this->acl->setPoll($poll)->request(Acl::PERMISSION_EDIT);
253
254
			if ($poll->getType() === Poll::TYPE_DATE) {
255
				throw new BadRequestException("Not allowed in date polls");
256
			}
257
		} catch (DoesNotExistException $e) {
258
			throw new NotAuthorizedException;
259
		}
260
261
		$i = 0;
262
		foreach ($options as $option) {
263
			$this->option = $this->optionMapper->find($option['id']);
264
			if ($pollId === intval($this->option->getPollId())) {
265
				$this->option->setOrder(++$i);
266
				$this->optionMapper->update($this->option);
267
			}
268
		}
269
270
		$this->watchService->writeUpdate($pollId, Watch::OBJECT_OPTIONS);
271
		return $this->optionMapper->findByPoll($pollId);
272
	}
273
274
	/**
275
	 * 	 * Change order for $optionId and reorder the options
276
	 *
277
	 * @NoAdminRequired
278
	 *
279
	 * @return Option[]
280
	 *
281
	 * @psalm-return array<array-key, Option>
282
	 */
283
	public function setOrder(int $optionId, int $newOrder): array {
284
		try {
285
			$this->option = $this->optionMapper->find($optionId);
286
			$poll = $this->pollMapper->find($this->option->getPollId());
287
			$this->acl->setPoll($poll)->request(Acl::PERMISSION_EDIT);
288
289
			if ($poll->getType() === Poll::TYPE_DATE) {
290
				throw new BadRequestException("Not allowed in date polls");
291
			}
292
		} catch (DoesNotExistException $e) {
293
			throw new NotAuthorizedException;
294
		}
295
296
		if ($newOrder < 1) {
297
			$newOrder = 1;
298
		} elseif ($newOrder > $this->getHighestOrder($poll->getId())) {
299
			$newOrder = $this->getHighestOrder($poll->getId());
300
		}
301
302
		foreach ($this->optionMapper->findByPoll($poll->getId()) as $option) {
303
			$option->setOrder($this->moveModifier($this->option->getOrder(), $newOrder, $option->getOrder()));
304
			$this->optionMapper->update($option);
305
		}
306
307
		$this->watchService->writeUpdate($this->option->getPollId(), Watch::OBJECT_OPTIONS);
308
		return $this->optionMapper->findByPoll($this->option->getPollId());
309
	}
310
311
	/**
312
	 * 	 * moveModifier - evaluate new order
313
	 * 	 * depending on the old and the new position of a moved array item
314
	 * 	 * $moveFrom - old position of the moved item
315
	 * 	 * $moveTo   - target posotion of the moved item
316
	 * 	 * $value    - current position of the current item
317
	 * 	 * Returns the modified new new position of the current item
318
	 *
319
	 * @return int
320
	 */
321
	private function moveModifier(int $moveFrom, int $moveTo, int $currentPosition): int {
322
		$moveModifier = 0;
323
		if ($moveFrom < $currentPosition && $currentPosition <= $moveTo) {
324
			// moving forward
325
			$moveModifier = -1;
326
		} elseif ($moveTo <= $currentPosition && $currentPosition < $moveFrom) {
327
			//moving backwards
328
			$moveModifier = 1;
329
		} elseif ($moveFrom === $currentPosition) {
330
			return $moveTo;
331
		}
332
		return $currentPosition + $moveModifier;
333
	}
334
335
	/**
336
	 * Set option entities validated
337
	 */
338
	private function setOption(int $timestamp = 0, ?string $pollOptionText = '', ?int $duration = 0): void {
339
		$poll = $this->pollMapper->find($this->option->getPollId());
340
341
		if ($poll->getType() === Poll::TYPE_DATE) {
342
			$this->option->setTimestamp($timestamp);
343
			$this->option->setOrder($timestamp);
344
			$this->option->setDuration($duration);
345
			if ($duration === 0) {
346
				$this->option->setPollOptionText(date('c', $timestamp));
347
			} elseif ($duration > 0) {
348
				$this->option->setPollOptionText(date('c', $timestamp) .' - ' . date('c', $timestamp + $duration));
349
			} else {
350
				$this->option->setPollOptionText($pollOptionText);
351
			}
352
		} else {
353
			$this->option->setPollOptionText($pollOptionText);
354
		}
355
	}
356
357
	/**
358
	 * 	 * Get the highest order number in $pollId
359
	 * 	 * Return Highest order number
360
	 *
361
	 * @return int
362
	 */
363
	private function getHighestOrder(int $pollId): int {
364
		$highestOrder = 0;
365
		foreach ($this->optionMapper->findByPoll($pollId) as $option) {
366
			if ($option->getOrder() > $highestOrder) {
367
				$highestOrder = $option->getOrder();
368
			}
369
		}
370
		return $highestOrder;
371
	}
372
}
373