Completed
Push — master ( 1b0cda...cf4dd3 )
by René
27s queued 11s
created

EventController::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 21
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 1
eloc 9
nc 1
nop 10
dl 0
loc 21
ccs 0
cts 21
cp 0
crap 2
rs 9.9666
c 1
b 0
f 0

How to fix   Many Parameters   

Many Parameters

Methods with many parameters are not only hard to understand, but their parameters also often become inconsistent when you need more, or different data.

There are several approaches to avoid long parameter lists:

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\Controller;
25
26
use Exception;
27
use OCP\AppFramework\Db\DoesNotExistException;
28
29
use OCP\IRequest;
30
use OCP\ILogger;
31
use OCP\AppFramework\Controller;
32
use OCP\AppFramework\Http;
33
use OCP\AppFramework\Http\DataResponse;
34
35
use OCP\IGroupManager;
36
use OCP\IUser;
37
use OCP\IUserManager;
38
use OCP\Security\ISecureRandom;
39
40
use OCA\Polls\Db\Event;
41
use OCA\Polls\Db\EventMapper;
42
use OCA\Polls\Service\EventService;
43
use OCA\Polls\Model\Acl;
44
45
class EventController extends Controller {
46
47
	private $userId;
48
	private $mapper;
49
	private $logger;
50
	private $groupManager;
51
	private $userManager;
52
	private $eventService;
53
	private $event;
54
	private $acl;
55
56
	/**
57
	 * CommentController constructor.
58
	 * @param string $appName
59
	 * @param $userId
60
	 * @param IRequest $request
61
	 * @param ILogger $logger
62
	 * @param EventMapper $mapper
63
	 * @param IGroupManager $groupManager
64
	 * @param IUserManager $userManager
65
	 * @param EventService $eventService
66
	 * @param Acl $acl
67
	 */
68
69
	public function __construct(
70
		string $appName,
71
		$userId,
72
		IRequest $request,
73
		ILogger $logger,
74
		EventMapper $mapper,
75
		Event $event,
76
		IGroupManager $groupManager,
77
		IUserManager $userManager,
78
		EventService $eventService,
79
		Acl $acl
80
	) {
81
		parent::__construct($appName, $request);
82
		$this->userId = $userId;
83
		$this->mapper = $mapper;
84
		$this->logger = $logger;
85
		$this->groupManager = $groupManager;
86
		$this->userManager = $userManager;
87
		$this->eventService = $eventService;
88
		$this->event = $event;
89
		$this->acl = $acl;
90
	}
91
92
	/**
93
	 * Get all polls
94
	 * @NoAdminRequired
95
	 * @NoCSRFRequired
96
	 * @return DataResponse
97
	 */
98
99
	public function list() {
100
		$events = [];
101
		if (\OC::$server->getUserSession()->isLoggedIn()) {
102
			try {
103
104
				$events = array_filter($this->mapper->findAll(), function($item) {
105
					if ($this->acl->setPollId($item->getId())->getAllowView()) {
106
						return true;
107
					} else {
108
						return false;
109
					}
110
    			});
111
			} catch (DoesNotExistException $e) {
112
				$events = [];
113
				// return new DataResponse($e, Http::STATUS_NOT_FOUND);
114
			}
115
		}
116
		return new DataResponse($events, Http::STATUS_OK);
117
	}
118
119
	/**
120
	 * Read an entire poll based on poll id
121
	 * @NoAdminRequired
122
	 * @NoCSRFRequired
123
	 * @PublicPage
124
	 * @param integer $pollId
125
	 * @return array
126
	 */
127
 	public function get($pollId) {
128
129
 		try {
130
			if (!$this->acl->getFoundByToken()) {
131
				$this->acl->setPollId($pollId);
132
			}
133
134
			$this->event = $this->mapper->find($pollId);
135
136
		} catch (DoesNotExistException $e) {
137
			$this->logger->info('Poll ' . $pollId . ' not found!', ['app' => 'polls']);
138
			return new DataResponse($e, Http::STATUS_NOT_FOUND);
139
 		}
140
141
		if ($this->event->getType() == 0) {
142
			$pollType = 'datePoll';
143
		} else {
144
			$pollType = 'textPoll';
145
		}
146
147
		// TODO: add migration for this
148
		if ($this->event->getAccess() === 'public' || $this->event->getAccess() === 'registered') {
149
			$this->event->setAccess('public');
150
		} else {
151
			$this->event->setAccess('hidden');
152
		}
153
154
		return new DataResponse((object) [
155
			'id' => $this->event->getId(),
156
			'type' => $pollType,
157
			'title' => $this->event->getTitle(),
158
			'description' => $this->event->getDescription(),
159
			'owner' => $this->event->getOwner(),
160
			'created' => $this->event->getCreated(),
161
			'access' => $this->event->getAccess(),
162
			'expire' => $this->event->getExpire(),
163
			'isAnonymous' => boolval($this->event->getIsAnonymous()),
164
			'fullAnonymous' => boolval($this->event->getFullAnonymous()),
165
			'allowMaybe' => boolval($this->event->getAllowMaybe()),
166
			'voteLimit' => $this->event->getVoteLimit(),
167
			'showResults' => $this->event->getShowResults(),
168
			'deleted' => boolval($this->event->getDeleted()),
169
			'deleteDate' => $this->event->getDeleteDate()
170
		],
171
		Http::STATUS_OK);
172
173
 	}
174
175
	/**
176
	 * getByToken
177
	 * Read all options of a poll based on a share token and return list as array
178
	 * @NoAdminRequired
179
	 * @PublicPage
180
	 * @NoCSRFRequired
181
	 * @param string $token
182
	 * @return DataResponse
183
	 */
184
	public function getByToken($token) {
185
186
		try {
187
			$this->acl->setToken($token);
188
		} catch (DoesNotExistException $e) {
189
			return new DataResponse($e, Http::STATUS_NOT_FOUND);
190
		}
191
		return $this->get($this->acl->getPollId());
192
193
	}
194
195
	/**
196
	 * Write poll (create/update)
197
	 * @NoAdminRequired
198
	 * @param Array $event
199
	 * @return DataResponse
200
	 */
201
202
	public function write($event) {
203
204
		try {
205
			// Find existing poll
206
			$this->event = $this->mapper->find($event['id']);
207
			$this->acl->setPollId($this->event->getId());
208
209
			if (!$this->acl->getAllowEdit()) {
210
				$this->logger->alert('Unauthorized write attempt from user ' . $this->userId);
211
				return new DataResponse('Unauthorized write attempt.', Http::STATUS_UNAUTHORIZED);
0 ignored issues
show
Bug introduced by
'Unauthorized write attempt.' of type string is incompatible with the type array|object expected by parameter $data of OCP\AppFramework\Http\DataResponse::__construct(). ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

211
				return new DataResponse(/** @scrutinizer ignore-type */ 'Unauthorized write attempt.', Http::STATUS_UNAUTHORIZED);
Loading history...
212
			}
213
214
			if ($this->event->getDeleted() !== $event['deleted']) {
215
				if ($event['deleted']) {
216
					$this->event->setDeleteDate(date('Y-m-d'));
0 ignored issues
show
Bug introduced by
date('Y-m-d') of type string is incompatible with the type integer expected by parameter $value of OCA\Polls\Db\Event::setDeleteDate(). ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

216
					$this->event->setDeleteDate(/** @scrutinizer ignore-type */ date('Y-m-d'));
Loading history...
217
				} else {
218
					$this->event->setDeleteDate('0');
219
				}
220
			}
221
			$this->event->setDeleted($event['deleted']);
222
		} catch (Exception $e) {
223
			$this->event = new Event();
224
			$this->acl->setPollId(0);
225
226
			if ($event['type'] === 'datePoll') {
227
				$this->event->setType(0);
228
			} elseif ($event['type'] === 'textPoll') {
229
				$this->event->setType(1);
230
			} else {
231
				$this->event->setType($event['type']);
232
			}
233
234
			$this->event->setOwner($this->userId);
235
			$this->event->setCreated(date('Y-m-d H:i:s',time()));
236
		} finally {
237
238
			$this->event->setTitle($event['title']);
239
			$this->event->setDescription($event['description']);
240
241
			$this->event->setAccess($event['access']);
242
			// $this->event->setExpire($event['expire']);
243
			if ($event['expire']) {
244
				$this->event->setExpire(date('Y-m-d H:i:s', strtotime($event['expire'])));
245
			} else {
246
				$this->event->setExpire(null);
247
			}
248
			$this->event->setIsAnonymous(intval($event['isAnonymous']));
249
			$this->event->setFullAnonymous(intval($event['fullAnonymous']));
250
			$this->event->setAllowMaybe(intval($event['allowMaybe']));
251
			// $this->event->setDeleteDate(time());
252
			$this->event->setVoteLimit(intval($event['voteLimit']));
253
			$this->event->setShowResults($event['showResults']);
254
255
			if ($this->acl->getPollId() > 0) {
256
				$this->mapper->update($this->event);
257
			} else {
258
				$this->mapper->insert($this->event);
259
			}
260
			$this->event = $this->get($this->event->getId());
261
			return new DataResponse($this->event, Http::STATUS_OK);
262
		}
263
	}
264
}
265