PageController::add()   B
last analyzed

Complexity

Conditions 6
Paths 7

Size

Total Lines 29

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 12
CRAP Score 7.3329

Importance

Changes 0
Metric Value
dl 0
loc 29
ccs 12
cts 18
cp 0.6667
rs 8.8337
c 0
b 0
f 0
cc 6
nc 7
nop 6
crap 7.3329
1
<?php
2
declare(strict_types=1);
3
/**
4
 * @copyright Copyright (c) 2016, Joas Schilling <[email protected]>
5
 *
6
 * @author Joas Schilling <[email protected]>
7
 *
8
 * @license GNU AGPL version 3 or any later version
9
 *
10
 * This program is free software: you can redistribute it and/or modify
11
 * it under the terms of the GNU Affero General Public License as
12
 * published by the Free Software Foundation, either version 3 of the
13
 * License, or (at your option) any later version.
14
 *
15
 * This program is distributed in the hope that it will be useful,
16
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
17
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
18
 * GNU Affero General Public License for more details.
19
 *
20
 * You should have received a copy of the GNU Affero General Public License
21
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
22
 *
23
 */
24
25
namespace OCA\AnnouncementCenter\Controller;
26
27
use OCA\AnnouncementCenter\Manager;
28
use OCA\AnnouncementCenter\Model\Announcement;
29
use OCP\AppFramework\Http;
30
use OCP\AppFramework\Http\JSONResponse;
31
use OCP\AppFramework\Http\TemplateResponse;
32
use OCP\AppFramework\Http\Response;
33
use OCP\AppFramework\Controller;
34
use OCP\AppFramework\Utility\ITimeFactory;
35
use OCP\BackgroundJob\IJobList;
36
use OCP\IConfig;
37
use OCP\IDBConnection;
38
use OCP\IGroupManager;
39
use OCP\IL10N;
40
use OCP\IRequest;
41
use OCP\IUser;
42
use OCP\IUserManager;
43
use OCP\IUserSession;
44
use OCA\AnnouncementCenter\BackgroundJob;
45
46
class PageController extends Controller {
47
48
	/** @var IJobList */
49
	protected $jobList;
50
51
	/** @var IDBConnection */
52
	protected $connection;
53
54
	/** @var IGroupManager */
55
	protected $groupManager;
56
57
	/** @var IUserManager */
58
	protected $userManager;
59
60
	/** @var IL10N */
61
	protected $l;
62
63
	/** @var Manager */
64
	protected $manager;
65
66
	/** @var IConfig */
67
	protected $config;
68
69
	/** @var ITimeFactory */
70
	protected $timeFactory;
71
72
	/** @var IUserSession */
73
	protected $userSession;
74
75 12
	public function __construct(string $AppName,
76
								IRequest $request,
77
								IDBConnection $connection,
78
								IGroupManager $groupManager,
79
								IUserManager $userManager,
80
								IJobList $jobList,
81
								IL10N $l,
82
								Manager $manager,
83
								IConfig $config,
84
								ITimeFactory $timeFactory,
85
								IUserSession $userSession) {
86 12
		parent::__construct($AppName, $request);
87
88 12
		$this->connection = $connection;
89 12
		$this->groupManager = $groupManager;
90 12
		$this->userManager = $userManager;
91 12
		$this->jobList = $jobList;
92 12
		$this->l = $l;
93 12
		$this->manager = $manager;
94 12
		$this->config = $config;
95 12
		$this->timeFactory = $timeFactory;
96 12
		$this->userSession = $userSession;
97 12
	}
98
99
	/**
100
	 * @NoAdminRequired
101
	 * @NoCSRFRequired
102
	 *
103
	 * @param int $offset
104
	 * @return JSONResponse
105
	 */
106
	public function get($offset = 0): JSONResponse {
107
		$announcements = $this->manager->getAnnouncements($offset);
108
		$data = array_map([$this, 'renderAnnouncement'], $announcements);
109
		return new JSONResponse($data);
110
	}
111
112
	/**
113
	 * @NoAdminRequired
114
	 *
115
	 * @param string $subject
116
	 * @param string $message
117
	 * @param string[] $groups,
0 ignored issues
show
Documentation introduced by
There is no parameter named $groups,. Did you maybe mean $groups?

This check looks for PHPDoc comments describing methods or function parameters that do not exist on the corresponding method or function. It has, however, found a similar but not annotated parameter which might be a good fit.

Consider the following example. The parameter $ireland is not defined by the method finale(...).

/**
 * @param array $germany
 * @param array $ireland
 */
function finale($germany, $island) {
    return "2:1";
}

The most likely cause is that the parameter was changed, but the annotation was not.

Loading history...
118
	 * @param bool $activities
119
	 * @param bool $notifications
120
	 * @param bool $comments
121
	 * @return JSONResponse
122
	 */
123 3
	public function add($subject, $message, array $groups, $activities, $notifications, $comments): JSONResponse {
124 3
		if (!$this->manager->checkIsAdmin()) {
125 1
			return new JSONResponse(
126 1
				['message' => 'Logged in user must be an admin'],
127 1
				Http::STATUS_FORBIDDEN
128
			);
129
		}
130 2
		$user = $this->userSession->getUser();
131 2
		$userId = $user instanceof IUser ? $user->getUID() : '';
0 ignored issues
show
Bug introduced by
The class OCP\IUser does not exist. Did you forget a USE statement, or did you not list all dependencies?

This error could be the result of:

1. Missing dependencies

PHP Analyzer uses your composer.json file (if available) to determine the dependencies of your project and to determine all the available classes and functions. It expects the composer.json to be in the root folder of your repository.

Are you sure this class is defined by one of your dependencies, or did you maybe not list a dependency in either the require or require-dev section?

2. Missing use statement

PHP does not complain about undefined classes in ìnstanceof checks. For example, the following PHP code will work perfectly fine:

if ($x instanceof DoesNotExist) {
    // Do something.
}

If you have not tested against this specific condition, such errors might go unnoticed.

Loading history...
132
133
		try {
134 2
			$announcement = $this->manager->announce($subject, $message, $userId, $this->timeFactory->getTime(), $groups, $comments);
135 2
		} catch (\InvalidArgumentException $e) {
136 2
			return new JSONResponse(
137 2
				['error' => $this->l->t('The subject is too long or empty')],
138 2
				Http::STATUS_BAD_REQUEST
139
			);
140
		}
141
142
		if ($activities || $notifications) {
143
			$this->jobList->add(BackgroundJob::class, [
144
				'id' => $announcement->getId(),
145
				'activities' => $activities,
146
				'notifications' => $notifications,
147
			]);
148
		}
149
150
		return new JSONResponse($this->renderAnnouncement($announcement));
151
	}
152
153
	protected function renderAnnouncement(Announcement $announcement): array {
154
		$displayName = $announcement->getUser();
155
		$user = $this->userManager->get($announcement->getUser());
156
		if ($user instanceof IUser) {
0 ignored issues
show
Bug introduced by
The class OCP\IUser does not exist. Did you forget a USE statement, or did you not list all dependencies?

This error could be the result of:

1. Missing dependencies

PHP Analyzer uses your composer.json file (if available) to determine the dependencies of your project and to determine all the available classes and functions. It expects the composer.json to be in the root folder of your repository.

Are you sure this class is defined by one of your dependencies, or did you maybe not list a dependency in either the require or require-dev section?

2. Missing use statement

PHP does not complain about undefined classes in ìnstanceof checks. For example, the following PHP code will work perfectly fine:

if ($x instanceof DoesNotExist) {
    // Do something.
}

If you have not tested against this specific condition, such errors might go unnoticed.

Loading history...
157
			$displayName = $user->getDisplayName();
158
		}
159
160
		$result = [
161
			'id'		=> $announcement->getId(),
162
			'author_id'	=> $announcement->getUser(),
163
			'author'	=> $displayName,
164
			'time'		=> $announcement->getTime(),
165
			'subject'	=> $announcement->getSubject(),
166
			'message'	=> $announcement->getParsedMessage(),
167
			'groups'	=> null,
168
			'comments'	=> $announcement->getAllowComments() ? $this->manager->getNumberOfComments($announcement) : false,
169
		];
170
171
		if ($this->manager->checkIsAdmin()) {
172
			$result['groups'] = $this->manager->getGroups($announcement);
173
			$result['notifications'] = $this->manager->hasNotifications($announcement);
174
		}
175
176
		return $result;
177
	}
178
179
	/**
180
	 * @NoAdminRequired
181
	 *
182
	 * @param int $id
183
	 * @return Response
184
	 */
185 2 View Code Duplication
	public function delete($id): Response {
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
186 2
		if (!$this->manager->checkIsAdmin()) {
187 1
			return new JSONResponse(
188 1
				['message' => 'Logged in user must be an admin'],
189 1
				Http::STATUS_FORBIDDEN
190
			);
191
		}
192
193 1
		$this->manager->delete($id);
194
195 1
		return new Response();
196
	}
197
198
	/**
199
	 * @NoAdminRequired
200
	 *
201
	 * @param int $id
202
	 * @return Response
203
	 */
204 View Code Duplication
	public function removeNotifications($id): Response {
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
205
		if (!$this->manager->checkIsAdmin()) {
206
			return new JSONResponse(
207
				['message' => 'Logged in user must be an admin'],
208
				Http::STATUS_FORBIDDEN
209
			);
210
		}
211
212
		$this->manager->removeNotifications($id);
213
214
		return new Response();
215
	}
216
217
	/**
218
	 * @NoAdminRequired
219
	 * @NoCSRFRequired
220
	 *
221
	 * @param int $announcement
222
	 * @return TemplateResponse
223
	 */
224 3
	public function index($announcement = 0): TemplateResponse {
225 3
		if ($announcement) {
226
			$this->manager->markNotificationRead($announcement);
227
		}
228
229 3
		return new TemplateResponse('announcementcenter', 'main', [
230 3
			'isAdmin'	=> $this->manager->checkIsAdmin(),
231 3
			'createActivities' => $this->config->getAppValue('announcementcenter', 'create_activities', 'yes') === 'yes',
232 3
			'createNotifications' => $this->config->getAppValue('announcementcenter', 'create_notifications', 'yes') === 'yes',
233 3
			'allowComments' => $this->config->getAppValue('announcementcenter', 'allow_comments', 'yes') === 'yes',
234
		]);
235
	}
236
237
	/**
238
	 * @NoAdminRequired
239
	 *
240
	 * @param string $pattern
241
	 * @return JSONResponse
242
	 */
243 3
	public function searchGroups($pattern): JSONResponse {
244 3
		if (!$this->manager->checkIsAdmin()) {
245 1
			return new JSONResponse(
246 1
				['message' => 'Logged in user must be an admin'],
247 1
				Http::STATUS_FORBIDDEN
248
			);
249
		}
250
251 2
		$groups = $this->groupManager->search($pattern, 10);
252 2
		$gids = [];
253 2
		foreach ($groups as $group) {
254 1
			$gids[] = $group->getGID();
255
		}
256
257 2
		return new JSONResponse($gids);
258
	}
259
}
260