Completed
Pull Request — master (#21)
by Joas
67:39 queued 31:40
created

EndpointController::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 8
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 7
CRAP Score 1

Importance

Changes 3
Bugs 0 Features 0
Metric Value
c 3
b 0
f 0
dl 0
loc 8
ccs 7
cts 7
cp 1
rs 9.4285
cc 1
eloc 6
nc 1
nop 6
crap 1
1
<?php
2
/**
3
 * @author Joas Schilling <[email protected]>
4
 *
5
 * @copyright Copyright (c) 2016, ownCloud, Inc.
6
 * @license AGPL-3.0
7
 *
8
 * This code is free software: you can redistribute it and/or modify
9
 * it under the terms of the GNU Affero General Public License, version 3,
10
 * as published by the Free Software Foundation.
11
 *
12
 * This program is distributed in the hope that it will be useful,
13
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15
 * GNU Affero General Public License for more details.
16
 *
17
 * You should have received a copy of the GNU Affero General Public License, version 3,
18
 * along with this program.  If not, see <http://www.gnu.org/licenses/>
19
 *
20
 */
21
22
namespace OCA\Notifications\Controller;
23
24
use OCA\Notifications\Handler;
25
use OCP\AppFramework\Http;
26
use OCP\AppFramework\Http\DataResponse;
27
use OCP\AppFramework\OCSController;
28
use OCP\IConfig;
29
use OCP\IRequest;
30
use OCP\IUser;
31
use OCP\IUserSession;
32
use OCP\Notification\IAction;
33
use OCP\Notification\IManager;
34
use OCP\Notification\INotification;
35
36
class EndpointController extends OCSController {
37
	/** @var Handler */
38
	private $handler;
39
40
	/** @var IManager */
41
	private $manager;
42
43
	/** @var IUserSession */
44
	private $session;
45
46
	/** @var IConfig */
47
	private $config;
48
49
	/**
50
	 * @param string $appName
51
	 * @param IRequest $request
52
	 * @param Handler $handler
53
	 * @param IManager $manager
54
	 * @param IConfig $config
55
	 * @param IUserSession $session
56
	 */
57 19
	public function __construct($appName, IRequest $request, Handler $handler, IManager $manager, IConfig $config, IUserSession $session) {
58 19
		parent::__construct($appName, $request);
59
60 19
		$this->handler = $handler;
61 19
		$this->manager = $manager;
62 19
		$this->config = $config;
63 19
		$this->session = $session;
64 19
	}
65
66
	/**
67
	 * @NoAdminRequired
68
	 * @NoCSRFRequired
69
	 *
70
	 * @return DataResponse
71
	 */
72 5
	public function listNotifications() {
73
		// When there are no apps registered that use the notifications
74
		// We stop polling for them.
75 5
		if (!$this->manager->hasNotifiers()) {
76 1
			return new DataResponse(null, Http::STATUS_NO_CONTENT);
77
		}
78
79 4
		$filter = $this->manager->createNotification();
80 4
		$filter->setUser($this->getCurrentUser());
81 4
		$language = $this->config->getUserValue($this->getCurrentUser(), 'core', 'lang', null);
82
83 4
		$notifications = $this->handler->get($filter);
84
85 4
		$data = [];
86 4
		$notificationIds = [];
87 4
		foreach ($notifications as $notificationId => $notification) {
88
			/** @var INotification $notification */
89
			try {
90 3
				$notification = $this->manager->prepare($notification, $language);
91 1
			} catch (\InvalidArgumentException $e) {
92
				// The app was disabled, skip the notification
93 1
				continue;
94
			}
95
96 3
			$notificationIds[] = $notificationId;
97 3
			$data[] = $this->notificationToArray($notificationId, $notification);
98
		}
99
100 4
		return new DataResponse($data, Http::STATUS_OK, ['ETag' => $this->generateEtag($notificationIds)]);
101
	}
102
103
	/**
104
	 * @NoAdminRequired
105
	 * @NoCSRFRequired
106
	 *
107
	 * @param int $id
108
	 * @return DataResponse
109
	 */
110 6
	public function getNotification($id = 0) {
111 6
		if (!$this->manager->hasNotifiers()) {
112 1
			return new DataResponse(null, Http::STATUS_NOT_FOUND);
113
		}
114
115 5 View Code Duplication
		if (!is_int($id) || $id === 0) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across 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...
116 5
			return new DataResponse(null, Http::STATUS_NOT_FOUND);
117
		}
118
119
		$notification = $this->handler->getById($id, $this->getCurrentUser());
120
121
		if (!($notification instanceof INotification)) {
0 ignored issues
show
Bug introduced by
The class OCP\Notification\INotification 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...
122
			return new DataResponse(null, Http::STATUS_NOT_FOUND);
123
		}
124
125
		$language = $this->config->getUserValue($this->getCurrentUser(), 'core', 'lang', null);
126
127
		try {
128
			$notification = $this->manager->prepare($notification, $language);
129
		} catch (\InvalidArgumentException $e) {
130
			// The app was disabled
131
			return new DataResponse(null, Http::STATUS_NOT_FOUND);
132
		}
133
134
		return new DataResponse($this->notificationToArray($id, $notification));
135
	}
136
137
	/**
138
	 * @NoAdminRequired
139
	 *
140
	 * @param int $id
141
	 * @return DataResponse
142
	 */
143 3
	public function deleteNotification($id = 0) {
144 3 View Code Duplication
		if (!is_int($id) || $id === 0) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across 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...
145 3
			return new DataResponse(null, Http::STATUS_NOT_FOUND);
146
		}
147
		$id = (int) $id;
148
149
		$this->handler->deleteById($id, $this->getCurrentUser());
150
		return new DataResponse();
151
	}
152
153
	/**
154
	 * Get an Etag for the notification ids
155
	 *
156
	 * @param array $notifications
157
	 * @return string
158
	 */
159 4
	protected function generateEtag(array $notifications) {
160 4
		return md5(json_encode($notifications));
161
	}
162
163
	/**
164
	 * @param int $notificationId
165
	 * @param INotification $notification
166
	 * @return array
167
	 */
168 2
	protected function notificationToArray($notificationId, INotification $notification) {
169
		$data = [
170 2
			'notification_id' => $notificationId,
171 2
			'app' => $notification->getApp(),
172 2
			'user' => $notification->getUser(),
173 2
			'datetime' => $notification->getDateTime()->format('c'),
174 2
			'object_type' => $notification->getObjectType(),
175 2
			'object_id' => $notification->getObjectId(),
176 2
			'subject' => $notification->getParsedSubject(),
177 2
			'message' => $notification->getParsedMessage(),
178 2
			'link' => $notification->getLink(),
179
			'actions' => [],
180
		];
181
182 2
		foreach ($notification->getParsedActions() as $action) {
183 1
			$data['actions'][] = $this->actionToArray($action);
184
		}
185
186 2
		return $data;
187
	}
188
189
	/**
190
	 * @param IAction $action
191
	 * @return array
192
	 */
193 2
	protected function actionToArray(IAction $action) {
194
		return [
195 2
			'label' => $action->getParsedLabel(),
196 2
			'link' => $action->getLink(),
197 2
			'type' => $action->getRequestType(),
198 2
			'primary' => $action->isPrimary(),
199
		];
200
	}
201
202
	/**
203
	 * @return string
204
	 */
205 4
	protected function getCurrentUser() {
206 4
		$user = $this->session->getUser();
207 4
		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...
208 4
			$user = $user->getUID();
209
		}
210
211 4
		return (string) $user;
212
	}
213
}
214