Completed
Pull Request — master (#32303)
by Victor
09:39
created

OcmController::createShare()   C

Complexity

Conditions 12
Paths 34

Size

Total Lines 88

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 12
nc 34
nop 11
dl 0
loc 88
rs 5.8351
c 0
b 0
f 0

How to fix   Long Method    Complexity    Many Parameters   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

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
 * @author Viktar Dubiniuk <[email protected]>
4
 *
5
 * @copyright Copyright (c) 2018, ownCloud GmbH
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\FederatedFileSharing\Controller;
23
24
use OCA\FederatedFileSharing\AddressHandler;
25
use OCP\AppFramework\Http\JSONResponse;
26
use OCA\FederatedFileSharing\Exception\InvalidShareException;
27
use OCA\FederatedFileSharing\Exception\NotSupportedException;
28
use OCA\FederatedFileSharing\FedShareManager;
29
use OCP\AppFramework\Controller;
30
use OCP\AppFramework\Http;
31
use OCP\ILogger;
32
use OCP\IRequest;
33
use OCP\IURLGenerator;
34
use OCP\IUserManager;
35
36
/**
37
 * Class OcmController
38
 *
39
 * @package OCA\FederatedFileSharing\Controller
40
 */
41
class OcmController extends Controller {
42
	const API_VERSION = '1.0-proposal1';
43
44
	/**
45
	 * @var IURLGenerator
46
	 */
47
	protected $urlGenerator;
48
49
	/**
50
	 * @var IUserManager
51
	 */
52
	protected $userManager;
53
54
	/**
55
	 * @var AddressHandler
56
	 */
57
	protected $addressHandler;
58
59
	/**
60
	 * @var FedShareManager
61
	 */
62
	protected $fedShareManager;
63
64
	/**
65
	 * @var ILogger
66
	 */
67
	protected $logger;
68
69
	/**
70
	 * OcmController constructor.
71
	 *
72
	 * @param string $appName
73
	 * @param IRequest $request
74
	 * @param IURLGenerator $urlGenerator
75
	 * @param IUserManager $userManager
76
	 * @param AddressHandler $addressHandler
77
	 * @param FedShareManager $fedShareManager
78
	 * @param ILogger $logger
79
	 */
80 View Code Duplication
	public function __construct($appName,
81
									IRequest $request,
82
									IURLGenerator $urlGenerator,
83
									IUserManager $userManager,
84
									AddressHandler $addressHandler,
85
									FedShareManager $fedShareManager,
86
									ILogger $logger
87
	) {
88
		parent::__construct($appName, $request);
89
90
		$this->urlGenerator = $urlGenerator;
91
		$this->userManager = $userManager;
92
		$this->addressHandler = $addressHandler;
93
		$this->fedShareManager = $fedShareManager;
94
		$this->logger = $logger;
95
	}
96
97
	/**
98
	 * @NoCSRFRequired
99
	 * @PublicPage
100
	 *
101
	 * EndPoint discovery
102
	 * Responds to /ocm-provider/ requests
103
	 *
104
	 * @return array
105
	 */
106
	public function discovery() {
107
		return [
108
			'enabled' => true,
109
			'apiVersion' => self::API_VERSION,
110
			'endPoint' => $this->urlGenerator->linkToRouteAbsolute(
111
				"{$this->appName}.ocm.index"
112
			),
113
			'shareTypes' => [
114
				'name' => 'file',
115
				'protocols' => $this->getProtocols()
116
			]
117
		];
118
	}
119
120
	/**
121
	 * @NoCSRFRequired
122
	 * @PublicPage
123
	 *
124
	 *
125
	 *
126
	 * @param string $shareWith identifier of the user or group
127
	 * 							to share the resource with
128
	 * @param string $name name of the shared resource
129
	 * @param string $description share description (optional)
130
	 * @param string $providerId Identifier of the resource at the provider side
131
	 * @param string $owner identifier of the user that owns the resource
132
	 * @param string $ownerDisplayName display name of the owner
133
	 * @param string $sender Provider specific identifier of the user that wants
134
	 * 							to share the resource
135
	 * @param string $senderDisplayName Display name of the user that wants
136
	 * 									to share the resource
137
	 * @param string $shareType Share type (user or group share)
138
	 * @param string $resourceType only 'file' is supported atm
139
	 * @param array $protocol
140
	 * 		[
141
	 * 			'name' => (string) protocol name. Only 'webdav' is supported atm,
142
	 * 			'options' => [
143
	 * 				protocol specific options
144
	 * 				only `webdav` options are supported atm
145
	 * 				e.g. `uri`,	`access_token`, `password`, `permissions` etc.
146
	 *
147
	 * 				For backward compatibility the webdav protocol will use
148
	 * 				the 'sharedSecret" as username and password
149
	 * 			]
150
	 *
151
	 */
152
	public function createShare($shareWith,
153
								$name,
154
								$description,
0 ignored issues
show
Unused Code introduced by
The parameter $description is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
155
								$providerId,
156
								$owner,
157
								$ownerDisplayName,
0 ignored issues
show
Unused Code introduced by
The parameter $ownerDisplayName is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
158
								$sender,
159
								$senderDisplayName,
0 ignored issues
show
Unused Code introduced by
The parameter $senderDisplayName is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
160
								$shareType,
161
								$resourceType,
162
								$protocol
163
164
	) {
165
		try {
166
			$hasMissingParams = $this->hasNull(
167
				[$shareWith, $name, $providerId, $owner, $shareType, $resourceType]
168
			);
169
			if ($hasMissingParams
170
				|| !is_array($protocol)
171
				|| !isset($protocol['name'])
172
				|| !isset($protocol['options'])
173
				|| !is_array($protocol['options'])
174
				|| !isset($protocol['options']['sharedSecret'])
175
			) {
176
				throw new InvalidShareException(
177
					'server can not add remote share, missing parameter'
178
				);
179
			}
180
			if (!\OCP\Util::isValidFileName($name)) {
181
				throw new InvalidShareException(
182
					'The mountpoint name contains invalid characters.'
183
				);
184
			}
185
			// FIXME this should be a method in the user management instead
186
			$this->logger->debug(
187
				"shareWith before, $shareWith",
188
				['app' => $this->appName]
189
			);
190
			\OCP\Util::emitHook(
191
				'\OCA\Files_Sharing\API\Server2Server',
192
				'preLoginNameUsedAsUserName',
193
				['uid' => &$shareWith]
194
			);
195
			$this->logger->debug(
196
				"shareWith after, $shareWith",
197
				['app' => $this->appName]
198
			);
199
200
			if (!$this->userManager->userExists($shareWith)) {
201
				throw new InvalidShareException('User does not exist');
202
			}
203
			$this->fedShareManager->createShare(
204
				$shareWith,
205
				$remote,
0 ignored issues
show
Bug introduced by
The variable $remote does not exist. Did you forget to declare it?

This check marks access to variables or properties that have not been declared yet. While PHP has no explicit notion of declaring a variable, accessing it before a value is assigned to it is most likely a bug.

Loading history...
206
				$remoteId, // TODO: remote id is excessive
0 ignored issues
show
Bug introduced by
The variable $remoteId does not exist. Did you forget to declare it?

This check marks access to variables or properties that have not been declared yet. While PHP has no explicit notion of declaring a variable, accessing it before a value is assigned to it is most likely a bug.

Loading history...
207
				$owner,
208
				$name,
209
				$ownerFederatedId, // TODO: $ownerFederatedId is excessive
0 ignored issues
show
Bug introduced by
The variable $ownerFederatedId does not exist. Did you forget to declare it?

This check marks access to variables or properties that have not been declared yet. While PHP has no explicit notion of declaring a variable, accessing it before a value is assigned to it is most likely a bug.

Loading history...
210
				$sharedByFederatedId, // TODO: $sharedByFederatedId is excessive
0 ignored issues
show
Bug introduced by
The variable $sharedByFederatedId does not exist. Did you forget to declare it?

This check marks access to variables or properties that have not been declared yet. While PHP has no explicit notion of declaring a variable, accessing it before a value is assigned to it is most likely a bug.

Loading history...
211
				$sender,
212
				$protocol['options']['sharedSecret']
213
			);
214
		} catch (InvalidShareException $e) {
215
			return new JSONResponse(
216
				null,
0 ignored issues
show
Documentation introduced by
null is of type null, but the function expects a array|object.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
217
				Http::STATUS_BAD_REQUEST,
218
				$e->getMessage()
0 ignored issues
show
Unused Code introduced by
The call to JSONResponse::__construct() has too many arguments starting with $e->getMessage().

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
219
			);
220
		} catch (NotSupportedException $e) {
221
			return new JSONResponse(
222
				null,
0 ignored issues
show
Documentation introduced by
null is of type null, but the function expects a array|object.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
223
				Http::STATUS_SERVICE_UNAVAILABLE,
224
				'Server does not support federated cloud sharing'
0 ignored issues
show
Unused Code introduced by
The call to JSONResponse::__construct() has too many arguments starting with 'Server does not support federated cloud sharing'.

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
225
			);
226
		} catch (\Exception $e) {
227
			\OCP\Util::writeLog(
228
				'files_sharing',
229
				'server can not add remote share, ' . $e->getMessage(),
230
				\OCP\Util::ERROR
231
			);
232
			return new JSONResponse(
233
				null,
0 ignored issues
show
Documentation introduced by
null is of type null, but the function expects a array|object.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
234
				Http::STATUS_INTERNAL_SERVER_ERROR,
235
				'internal server error, was not able to add share from ' . $remote
0 ignored issues
show
Unused Code introduced by
The call to JSONResponse::__construct() has too many arguments starting with 'internal server error, ... share from ' . $remote.

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
236
			);
237
		}
238
		return new JSONResponse();
239
	}
240
241
	/**
242
	 * @param string $notificationType notification type (SHARE_REMOVED, etc)
243
	 * @param string $resourceType only 'file' is supported atm
244
	 * @param string $providerId Identifier of the resource at the provider side
245
	 * @param array $notification
246
	 * 		[
247
	 * 			optional additional parameters, depending on the notification
248
	 * 				and the resource type
249
	 * 		]
250
	 */
251
	public function processNotification($notificationType,
0 ignored issues
show
Unused Code introduced by
The parameter $notificationType is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
252
										$resourceType,
0 ignored issues
show
Unused Code introduced by
The parameter $resourceType is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
253
										$providerId,
0 ignored issues
show
Unused Code introduced by
The parameter $providerId is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
254
										$notification
0 ignored issues
show
Unused Code introduced by
The parameter $notification is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
255
	) {
256
		// TODO: implement
257
	}
258
259
	protected function getProtocols() {
260
		return [
261
			'webdav' => '/public.php/webdav/'
262
		];
263
	}
264
265
	/**
266
	 * Check if value is null or an array has any null item
267
	 *
268
	 * @param mixed $param
269
	 *
270
	 * @return bool
271
	 */
272 View Code Duplication
	protected function hasNull($param) {
273
		if (\is_array($param)) {
274
			return \in_array(null, $param, true);
275
		} else {
276
			return $param === null;
277
		}
278
	}
279
}
280