Passed
Pull Request — master (#1254)
by René
03:50
created

OptionService::moveModifier()   A

Complexity

Conditions 6
Paths 4

Size

Total Lines 12
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 42

Importance

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