Passed
Pull Request — master (#1219)
by René
04:40
created

OptionService::get()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 6
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 6

Importance

Changes 0
Metric Value
eloc 3
c 0
b 0
f 0
dl 0
loc 6
ccs 0
cts 3
cp 0
rs 10
cc 2
nc 2
nop 1
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 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
		$acl = $this->acl->set($pollId, $token);
84
85
		if (!$acl->getAllowView()) {
86
			throw new NotAuthorizedException;
87
		}
88
89
		try {
90
			return $this->optionMapper->findByPoll($acl->getPollId());
91
		} catch (DoesNotExistException $e) {
92
			return [];
93
		}
94
	}
95
96
	/**
97
	 * Get option
98
	 * @NoAdminRequired
99
	 * @param int $optionId
100
	 * @return Option
101
	 * @throws NotAuthorizedException
102
	 */
103
	public function get($optionId) {
104
		if (!$this->acl->set($this->optionMapper->find($optionId)->getPollId())->getAllowView()) {
105
			throw new NotAuthorizedException;
106
		}
107
108
		return $this->optionMapper->find($optionId);
109
	}
110
111
112
	/**
113
	 * Add a new option
114
	 * @NoAdminRequired
115
	 * @param int $pollId
116
	 * @param int $timestamp
117
	 * @param string $pollOptionText
118
	 * @return Option
119
	 * @throws NotAuthorizedException
120
	 */
121
	public function add($pollId, $timestamp = 0, $pollOptionText = '') {
122
		if (!$this->acl->set($pollId)->getAllowEdit()) {
123
			throw new NotAuthorizedException;
124
		}
125
126
		$this->option = new Option();
127
		$this->option->setPollId($pollId);
128
		$this->option->setOrder($this->getHighestOrder($this->option->getPollId()) + 1);
129
		$this->setOption($timestamp, $pollOptionText);
130
131
		try {
132
			return $this->optionMapper->insert($this->option);
133
		} catch (UniqueConstraintViolationException $e) {
134
			throw new DuplicateEntryException('This option already exists');
135
		}
136
	}
137
138
	/**
139
	 * Update option
140
	 * @NoAdminRequired
141
	 * @param int $optionId
142
	 * @param int $timestamp
143
	 * @param string $pollOptionText
144
	 * @param int $order
145
	 * @return Option
146
	 * @throws NotAuthorizedException
147
	 */
148
	public function update($optionId, $timestamp = 0, $pollOptionText = '') {
149
		$this->option = $this->optionMapper->find($optionId);
150
151
		if (!$this->acl->set($this->option->getPollId())->getAllowEdit()) {
152
			throw new NotAuthorizedException;
153
		}
154
155
		$this->setOption($timestamp, $pollOptionText);
156
157
		return $this->optionMapper->update($this->option);
158
	}
159
160
	/**
161
	 * Delete option
162
	 * @NoAdminRequired
163
	 * @param int $optionId
164
	 * @return Option deleted Option
165
	 * @throws NotAuthorizedException
166
	 */
167
	public function delete($optionId) {
168
		$this->option = $this->optionMapper->find($optionId);
169
170
		if (!$this->acl->set($this->option->getPollId())->getAllowEdit()) {
171
			throw new NotAuthorizedException;
172
		}
173
174
		$this->optionMapper->delete($this->option);
175
176
		return $this->option;
177
	}
178
179
	/**
180
	 * Switch optoin confirmation
181
	 * @NoAdminRequired
182
	 * @param int $optionId
183
	 * @return Option confirmed Option
184
	 * @throws NotAuthorizedException
185
	 */
186
	public function confirm($optionId) {
187
		$this->option = $this->optionMapper->find($optionId);
188
189
		if (!$this->acl->set($this->option->getPollId())->getAllowEdit()) {
190
			throw new NotAuthorizedException;
191
		}
192
193
		if ($this->option->getConfirmed()) {
194
			$this->option->setConfirmed(0);
195
		} else {
196
			$this->option->setConfirmed(time());
197
		}
198
199
		return $this->optionMapper->update($this->option);
200
	}
201
202
	/**
203
	 * Make a sequence of date poll options
204
	 * @NoAdminRequired
205
	 * @param int $optionId
206
	 * @param int $step
207
	 * @param string $unit
208
	 * @param int $amount
209
	 * @return array Array of Option objects
210
	 * @throws NotAuthorizedException
211
	 */
212
	public function sequence($optionId, $step, $unit, $amount) {
213
		$baseDate = new DateTime;
214
		$origin = $this->optionMapper->find($optionId);
215
216
		if (!$this->acl->set($origin->getPollId())->getAllowEdit()) {
217
			throw new NotAuthorizedException;
218
		}
219
220
		if ($step === 0) {
221
			return $this->optionMapper->findByPoll($origin->getPollId());
222
		}
223
224
		$baseDate->setTimestamp($origin->getTimestamp());
225
226
		for ($i = 0; $i < $amount; $i++) {
227
			$this->option = new Option();
228
			$this->option->setPollId($origin->getPollId());
229
			$this->option->setConfirmed(0);
230
			$this->option->setTimestamp($baseDate->modify($step . ' ' . $unit)->getTimestamp());
231
			$this->option->setPollOptionText($baseDate->format('c'));
232
			$this->option->setOrder($baseDate->getTimestamp());
233
			try {
234
				$this->optionMapper->insert($this->option);
235
			} catch (UniqueConstraintViolationException $e) {
236
				\OC::$server->getLogger()->warning('skip adding ' . $baseDate->format('c') . 'for pollId' . $origin->getPollId() . '. Option alredy exists.');
237
			}
238
		}
239
		return $this->optionMapper->findByPoll($origin->getPollId());
240
	}
241
242
	/**
243
	 * Copy options from $fromPoll to $toPoll
244
	 * @NoAdminRequired
245
	 * @param int $fromPollId
246
	 * @param int $toPollId
247
	 * @return array Array of Option objects
248
	 * @throws NotAuthorizedException
249
	 */
250
	public function clone($fromPollId, $toPollId) {
251
		try {
252
			if (!$this->acl->set($fromPollId)->getAllowView()) {
253
				throw new NotAuthorizedException;
254
			}
255
		} catch (DoesNotExistException $e) {
256
			throw new NotFoundException('Poll ' . $fromPollId .' does not exist');
257
		}
258
259
		foreach ($this->optionMapper->findByPoll($fromPollId) as $origin) {
260
			$option = new Option();
261
			$option->setPollId($toPollId);
262
			$option->setConfirmed(0);
263
			$option->setPollOptionText($origin->getPollOptionText());
264
			$option->setTimestamp($origin->getTimestamp());
265
			$option->setOrder($origin->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
	 * @NoAdminRequired
275
	 * @param int $pollId
276
	 * @param array $options - Array of options
277
	 * @return array Array of Option objects
278
	 * @throws NotAuthorizedException
279
	 * @throws BadRequestException
280
	 * @throws NotFoundException
281
	 */
282
	public function reorder($pollId, $options) {
283
		try {
284
			if (!$this->acl->set($pollId)->getAllowEdit()) {
285
				throw new NotAuthorizedException;
286
			}
287
288
			if ($this->pollMapper->find($pollId)->getType() === Poll::TYPE_DATE) {
289
				throw new BadRequestException("Not allowed in date polls");
290
			}
291
		} catch (DoesNotExistException $e) {
292
			throw new NotAuthorizedException;
293
		}
294
295
		$i = 0;
296
		foreach ($options as $option) {
297
			$this->option = $this->optionMapper->find($option['id']);
298
			if ($pollId === intval($this->option->getPollId())) {
299
				$this->option->setOrder(++$i);
300
				$this->optionMapper->update($this->option);
301
			}
302
		}
303
304
		return $this->optionMapper->findByPoll($pollId);
305
	}
306
307
	/**
308
	 * Change order for $optionId and reorder the options
309
	 * @NoAdminRequired
310
	 * @param int $optionId
311
	 * @param int $newOrder
312
	 * @return array Array of Option objects
313
	 * @throws NotAuthorizedException
314
	 * @throws BadRequestException
315
	 * @throws NotFoundException
316
	 */
317
	public function setOrder($optionId, $newOrder) {
318
		try {
319
			$this->option = $this->optionMapper->find($optionId);
320
			$pollId = $this->option->getPollId();
321
322
			if ($this->pollMapper->find($pollId)->getType() === Poll::TYPE_DATE) {
323
				throw new BadRequestException("Not allowed in date polls");
324
			}
325
326
			if (!$this->acl->set($pollId)->getAllowEdit()) {
327
				throw new NotAuthorizedException;
328
			}
329
		} catch (DoesNotExistException $e) {
330
			throw new NotAuthorizedException;
331
		}
332
333
		if ($newOrder < 1) {
334
			$newOrder = 1;
335
		} elseif ($newOrder > $this->getHighestOrder($pollId)) {
336
			$newOrder = $this->getHighestOrder($pollId);
337
		}
338
339
		foreach ($this->optionMapper->findByPoll($pollId) as $option) {
340
			$option->setOrder($this->moveModifier($this->option->getOrder(), $newOrder, $option->getOrder()));
341
			$this->optionMapper->update($option);
342
		}
343
344
		return $this->optionMapper->findByPoll($this->option->getPollId());
345
	}
346
347
	/**
348
	 * moveModifier - evaluate new order
349
	 * depending on the old and the new position of a moved array item
350
	 * @NoAdminRequired
351
	 * @param int $moveFrom - old position of the moved item
352
	 * @param int $moveTo   - target posotion of the moved item
353
	 * @param int $value    - current position of the current item
354
	 * @return int          - the modified new new position of the current item
355
	 */
356
	private function moveModifier($moveFrom, $moveTo, $currentPosition) {
357
		$moveModifier = 0;
358
		if ($moveFrom < $currentPosition && $currentPosition <= $moveTo) {
359
			// moving forward
360
			$moveModifier = -1;
361
		} elseif ($moveTo <= $currentPosition && $currentPosition < $moveFrom) {
362
			//moving backwards
363
			$moveModifier = 1;
364
		} elseif ($moveFrom === $currentPosition) {
365
			return $moveTo;
366
		}
367
		return $currentPosition + $moveModifier;
368
	}
369
370
	/**
371
	 * Set option entities validated
372
	 * @NoAdminRequired
373
	 * @param int $timestamp
374
	 * @param string $pollOptionText
375
	 * @param int $order
376
	 * @throws BadRequestException
377
	 */
378
	private function setOption($timestamp = 0, $pollOptionText = '') {
379
		$poll = $this->pollMapper->find($this->option->getPollId());
380
381
		if ($poll->getType() === Poll::TYPE_DATE) {
382
			$this->option->setTimestamp($timestamp);
383
			$this->option->setOrder($timestamp);
384
			$this->option->setPollOptionText(date('c', $timestamp));
385
		} else {
386
			$this->option->setPollOptionText($pollOptionText);
387
		}
388
	}
389
390
	/**
391
	 * Get the highest order number in $pollId
392
	 * @NoAdminRequired
393
	 * @param int $pollId
394
	 * @return int Highest order number
395
	 */
396
	private function getHighestOrder($pollId) {
397
		$highestOrder = 0;
398
		foreach ($this->optionMapper->findByPoll($pollId) as $option) {
399
			if ($option->getOrder() > $highestOrder) {
400
				$highestOrder = $option->getOrder();
401
			}
402
		}
403
		return $highestOrder;
404
	}
405
}
406