Completed
Push — master ( 88f2dc...58f7d6 )
by René
26s queued 12s
created

OptionService   B

Complexity

Total Complexity 43

Size/Duplication

Total Lines 324
Duplicated Lines 0 %

Test Coverage

Coverage 0%

Importance

Changes 4
Bugs 3 Features 0
Metric Value
wmc 43
eloc 143
dl 0
loc 324
ccs 0
cts 169
cp 0
rs 8.96
c 4
b 3
f 0

14 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 12 1
A list() 0 15 4
A get() 0 8 2
A delete() 0 7 1
A add() 0 14 2
A update() 0 8 1
A confirm() 0 8 2
A moveModifier() 0 12 6
A setOrder() 0 26 6
A getHighestOrder() 0 6 3
A clone() 0 15 2
A reorder() 0 23 5
A setOption() 0 16 4
A sequence() 0 27 4

How to fix   Complexity   

Complex Class

Complex classes like OptionService often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

While breaking up the class, it is a good idea to analyze how other classes use OptionService, and based on these observations, apply Extract Interface, too.

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
		$this->option->setConfirmed($this->option->getConfirmed() ? 0 : time());
172
		$this->option = $this->optionMapper->update($this->option);
173
		$this->watchService->writeUpdate($this->option->getPollId(), Watch::OBJECT_OPTIONS);
174
		return $this->option;
175
	}
176
177
	/**
178
	 * 	 * Make a sequence of date poll options
179
	 *
180
	 * @return Option[]
181
	 *
182
	 * @psalm-return array<array-key, Option>
183
	 */
184
	public function sequence(int $optionId, int $step, string $unit, int $amount): array {
185
		$baseDate = new DateTime;
186
		$this->option = $this->optionMapper->find($optionId);
187
		$this->acl->setPollId($this->option->getPollId())->request(Acl::PERMISSION_EDIT);
188
189
		if ($step === 0) {
190
			return $this->optionMapper->findByPoll($this->option->getPollId());
191
		}
192
193
		$baseDate->setTimestamp($this->option->getTimestamp());
194
195
		for ($i = 0; $i < $amount; $i++) {
196
			$clonedOption = new Option();
197
			$clonedOption->setPollId($this->option->getPollId());
198
			$clonedOption->setDuration($this->option->getDuration());
199
			$clonedOption->setConfirmed(0);
200
			$clonedOption->setTimestamp($baseDate->modify($step . ' ' . $unit)->getTimestamp());
201
			$clonedOption->setOrder($clonedOption->getTimestamp());
202
			$clonedOption->setPollOptionText($baseDate->format('c'));
203
			try {
204
				$this->optionMapper->insert($clonedOption);
205
			} catch (UniqueConstraintViolationException $e) {
206
				\OC::$server->getLogger()->warning('skip adding ' . $baseDate->format('c') . 'for pollId' . $this->option->getPollId() . '. Option alredy exists.');
207
			}
208
		}
209
		$this->watchService->writeUpdate($this->option->getPollId(), Watch::OBJECT_OPTIONS);
210
		return $this->optionMapper->findByPoll($this->option->getPollId());
211
	}
212
213
	/**
214
	 * 	 * Copy options from $fromPoll to $toPoll
215
	 *
216
	 * @return Option[]
217
	 *
218
	 * @psalm-return array<array-key, Option>
219
	 */
220
	public function clone(int $fromPollId, int $toPollId): array {
221
		$this->acl->setPollId($fromPollId);
222
223
		foreach ($this->optionMapper->findByPoll($fromPollId) as $origin) {
224
			$option = new Option();
225
			$option->setPollId($toPollId);
226
			$option->setConfirmed(0);
227
			$option->setPollOptionText($origin->getPollOptionText());
228
			$option->setTimestamp($origin->getTimestamp());
229
			$option->setDuration($origin->getDuration());
230
			$option->setOrder($option->getOrder());
231
			$this->optionMapper->insert($option);
232
		}
233
234
		return $this->optionMapper->findByPoll($toPollId);
235
	}
236
237
	/**
238
	 * 	 * Reorder options with the order specified by $options
239
	 *
240
	 * @return Option[]
241
	 *
242
	 * @psalm-return array<array-key, Option>
243
	 */
244
	public function reorder(int $pollId, array $options): array {
245
		try {
246
			$poll = $this->pollMapper->find($pollId);
247
			$this->acl->setPoll($poll)->request(Acl::PERMISSION_EDIT);
248
249
			if ($poll->getType() === Poll::TYPE_DATE) {
250
				throw new BadRequestException("Not allowed in date polls");
251
			}
252
		} catch (DoesNotExistException $e) {
253
			throw new NotAuthorizedException;
254
		}
255
256
		$i = 0;
257
		foreach ($options as $option) {
258
			$this->option = $this->optionMapper->find($option['id']);
259
			if ($pollId === intval($this->option->getPollId())) {
260
				$this->option->setOrder(++$i);
261
				$this->optionMapper->update($this->option);
262
			}
263
		}
264
265
		$this->watchService->writeUpdate($pollId, Watch::OBJECT_OPTIONS);
266
		return $this->optionMapper->findByPoll($pollId);
267
	}
268
269
	/**
270
	 * 	 * Change order for $optionId and reorder the options
271
	 *
272
	 * @NoAdminRequired
273
	 *
274
	 * @return Option[]
275
	 *
276
	 * @psalm-return array<array-key, Option>
277
	 */
278
	public function setOrder(int $optionId, int $newOrder): array {
279
		try {
280
			$this->option = $this->optionMapper->find($optionId);
281
			$poll = $this->pollMapper->find($this->option->getPollId());
282
			$this->acl->setPoll($poll)->request(Acl::PERMISSION_EDIT);
283
284
			if ($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
		if ($newOrder < 1) {
292
			$newOrder = 1;
293
		} elseif ($newOrder > $this->getHighestOrder($poll->getId())) {
294
			$newOrder = $this->getHighestOrder($poll->getId());
295
		}
296
297
		foreach ($this->optionMapper->findByPoll($poll->getId()) as $option) {
298
			$option->setOrder($this->moveModifier($this->option->getOrder(), $newOrder, $option->getOrder()));
299
			$this->optionMapper->update($option);
300
		}
301
302
		$this->watchService->writeUpdate($this->option->getPollId(), Watch::OBJECT_OPTIONS);
303
		return $this->optionMapper->findByPoll($this->option->getPollId());
304
	}
305
306
	/**
307
	 * 	 * moveModifier - evaluate new order
308
	 * 	 * depending on the old and the new position of a moved array item
309
	 * 	 * $moveFrom - old position of the moved item
310
	 * 	 * $moveTo   - target posotion of the moved item
311
	 * 	 * $value    - current position of the current item
312
	 * 	 * Returns the modified new new position of the current item
313
	 *
314
	 * @return int
315
	 */
316
	private function moveModifier(int $moveFrom, int $moveTo, int $currentPosition): int {
317
		$moveModifier = 0;
318
		if ($moveFrom < $currentPosition && $currentPosition <= $moveTo) {
319
			// moving forward
320
			$moveModifier = -1;
321
		} elseif ($moveTo <= $currentPosition && $currentPosition < $moveFrom) {
322
			//moving backwards
323
			$moveModifier = 1;
324
		} elseif ($moveFrom === $currentPosition) {
325
			return $moveTo;
326
		}
327
		return $currentPosition + $moveModifier;
328
	}
329
330
	/**
331
	 * Set option entities validated
332
	 */
333
	private function setOption(int $timestamp = 0, ?string $pollOptionText = '', ?int $duration = 0): void {
334
		$poll = $this->pollMapper->find($this->option->getPollId());
335
336
		if ($poll->getType() === Poll::TYPE_DATE) {
337
			$this->option->setTimestamp($timestamp);
338
			$this->option->setOrder($timestamp);
339
			$this->option->setDuration($duration);
340
			if ($duration === 0) {
341
				$this->option->setPollOptionText(date('c', $timestamp));
342
			} elseif ($duration > 0) {
343
				$this->option->setPollOptionText(date('c', $timestamp) .' - ' . date('c', $timestamp + $duration));
344
			} else {
345
				$this->option->setPollOptionText($pollOptionText);
346
			}
347
		} else {
348
			$this->option->setPollOptionText($pollOptionText);
349
		}
350
	}
351
352
	/**
353
	 * 	 * Get the highest order number in $pollId
354
	 * 	 * Return Highest order number
355
	 *
356
	 * @return int
357
	 */
358
	private function getHighestOrder(int $pollId): int {
359
		$highestOrder = 0;
360
		foreach ($this->optionMapper->findByPoll($pollId) as $option) {
361
			$highestOrder = ($option->getOrder() > $highestOrder) ? $option->getOrder() : $highestOrder;
362
		}
363
		return $highestOrder;
364
	}
365
}
366