Completed
Pull Request — master (#32303)
by Victor
11:10
created

OcmController::createShare()   C

Complexity

Conditions 12
Paths 40

Size

Total Lines 88

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 12
nc 40
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\Address;
25
use OCA\FederatedFileSharing\AddressHandler;
26
use OCP\AppFramework\Http\JSONResponse;
27
use OCA\FederatedFileSharing\Exception\InvalidShareException;
28
use OCA\FederatedFileSharing\Exception\NotSupportedException;
29
use OCA\FederatedFileSharing\FedShareManager;
30
use OCP\AppFramework\Controller;
31
use OCP\AppFramework\Http;
32
use OCP\ILogger;
33
use OCP\IRequest;
34
use OCP\IURLGenerator;
35
use OCP\IUserManager;
36
37
/**
38
 * Class OcmController
39
 *
40
 * @package OCA\FederatedFileSharing\Controller
41
 */
42
class OcmController extends Controller {
43
	const API_VERSION = '1.0-proposal1';
44
45
	/**
46
	 * @var IURLGenerator
47
	 */
48
	protected $urlGenerator;
49
50
	/**
51
	 * @var IUserManager
52
	 */
53
	protected $userManager;
54
55
	/**
56
	 * @var AddressHandler
57
	 */
58
	protected $addressHandler;
59
60
	/**
61
	 * @var FedShareManager
62
	 */
63
	protected $fedShareManager;
64
65
	/**
66
	 * @var ILogger
67
	 */
68
	protected $logger;
69
70
	/**
71
	 * OcmController constructor.
72
	 *
73
	 * @param string $appName
74
	 * @param IRequest $request
75
	 * @param IURLGenerator $urlGenerator
76
	 * @param IUserManager $userManager
77
	 * @param AddressHandler $addressHandler
78
	 * @param FedShareManager $fedShareManager
79
	 * @param ILogger $logger
80
	 */
81 View Code Duplication
	public function __construct($appName,
82
									IRequest $request,
83
									IURLGenerator $urlGenerator,
84
									IUserManager $userManager,
85
									AddressHandler $addressHandler,
86
									FedShareManager $fedShareManager,
87
									ILogger $logger
88
	) {
89
		parent::__construct($appName, $request);
90
91
		$this->urlGenerator = $urlGenerator;
92
		$this->userManager = $userManager;
93
		$this->addressHandler = $addressHandler;
94
		$this->fedShareManager = $fedShareManager;
95
		$this->logger = $logger;
96
	}
97
98
	/**
99
	 * @NoCSRFRequired
100
	 * @PublicPage
101
	 *
102
	 * EndPoint discovery
103
	 * Responds to /ocm-provider/ requests
104
	 *
105
	 * @return array
106
	 */
107
	public function discovery() {
108
		return [
109
			'enabled' => true,
110
			'apiVersion' => self::API_VERSION,
111
			'endPoint' => $this->urlGenerator->linkToRouteAbsolute(
112
				"{$this->appName}.ocm.index"
113
			),
114
			'shareTypes' => [
115
				'name' => 'file',
116
				'protocols' => $this->getProtocols()
117
			]
118
		];
119
	}
120
121
	/**
122
	 * @NoCSRFRequired
123
	 * @PublicPage
124
	 *
125
	 *
126
	 *
127
	 * @param string $shareWith identifier of the user or group
128
	 * 							to share the resource with
129
	 * @param string $name name of the shared resource
130
	 * @param string $description share description (optional)
131
	 * @param string $providerId Identifier of the resource at the provider side
132
	 * @param string $owner identifier of the user that owns the resource
133
	 * @param string $ownerDisplayName display name of the owner
134
	 * @param string $sender Provider specific identifier of the user that wants
135
	 * 							to share the resource
136
	 * @param string $senderDisplayName Display name of the user that wants
137
	 * 									to share the resource
138
	 * @param string $shareType Share type (user or group share)
139
	 * @param string $resourceType only 'file' is supported atm
140
	 * @param array $protocol
141
	 * 		[
142
	 * 			'name' => (string) protocol name. Only 'webdav' is supported atm,
143
	 * 			'options' => [
144
	 * 				protocol specific options
145
	 * 				only `webdav` options are supported atm
146
	 * 				e.g. `uri`,	`access_token`, `password`, `permissions` etc.
147
	 *
148
	 * 				For backward compatibility the webdav protocol will use
149
	 * 				the 'sharedSecret" as username and password
150
	 * 			]
151
	 *
152
	 */
153
	public function createShare($shareWith,
154
								$name,
155
								$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...
156
								$providerId,
157
								$owner,
158
								$ownerDisplayName,
159
								$sender,
160
								$senderDisplayName,
161
								$shareType,
162
								$resourceType,
163
								$protocol
164
165
	) {
166
		try {
167
			$hasMissingParams = $this->hasNull(
168
				[$shareWith, $name, $providerId, $owner, $shareType, $resourceType]
169
			);
170
			if ($hasMissingParams
171
				|| !\is_array($protocol)
172
				|| !isset($protocol['name'])
173
				|| !isset($protocol['options'])
174
				|| !\is_array($protocol['options'])
175
				|| !isset($protocol['options']['sharedSecret'])
176
			) {
177
				throw new InvalidShareException(
178
					'server can not add remote share, missing parameter'
179
				);
180
			}
181
			if (!\OCP\Util::isValidFileName($name)) {
182
				throw new InvalidShareException(
183
					'The mountpoint name contains invalid characters.'
184
				);
185
			}
186
			// FIXME this should be a method in the user management instead
187
			$this->logger->debug(
188
				"shareWith before, $shareWith",
189
				['app' => $this->appName]
190
			);
191
			\OCP\Util::emitHook(
192
				'\OCA\Files_Sharing\API\Server2Server',
193
				'preLoginNameUsedAsUserName',
194
				['uid' => &$shareWith]
195
			);
196
			$this->logger->debug(
197
				"shareWith after, $shareWith",
198
				['app' => $this->appName]
199
			);
200
201
			if (!$this->userManager->userExists($shareWith)) {
202
				throw new InvalidShareException("User $shareWith does not exist");
203
			}
204
205
			$ownerAddress = new Address($owner, $ownerDisplayName);
206
			$sharedByAddress = new Address($sender, $senderDisplayName);
207
208
			$this->fedShareManager->createShare(
209
				$ownerAddress,
210
				$sharedByAddress,
211
				$shareWith,
212
				$providerId,
213
				$name,
214
				$protocol['options']['sharedSecret']
215
			);
216
		} catch (InvalidShareException $e) {
217
			return new JSONResponse(
218
				['message' => $e->getMessage()],
219
				Http::STATUS_BAD_REQUEST
220
			);
221
		} catch (NotSupportedException $e) {
222
			return new JSONResponse(
223
				['message' => 'Server does not support federated cloud sharing'],
224
				Http::STATUS_SERVICE_UNAVAILABLE
225
			);
226
		} catch (\Exception $e) {
227
			$this->logger->error(
228
				"server can not add remote share, {$e->getMessage()}",
229
				['app' => 'federatefilesharing']
230
			);
231
			return new JSONResponse(
232
				['message' => "internal server error, was not able to add share from {$ownerAddress->getHostName()}"],
0 ignored issues
show
Bug introduced by
The variable $ownerAddress does not seem to be defined for all execution paths leading up to this point.

If you define a variable conditionally, it can happen that it is not defined for all execution paths.

Let’s take a look at an example:

function myFunction($a) {
    switch ($a) {
        case 'foo':
            $x = 1;
            break;

        case 'bar':
            $x = 2;
            break;
    }

    // $x is potentially undefined here.
    echo $x;
}

In the above example, the variable $x is defined if you pass “foo” or “bar” as argument for $a. However, since the switch statement has no default case statement, if you pass any other value, the variable $x would be undefined.

Available Fixes

  1. Check for existence of the variable explicitly:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        if (isset($x)) { // Make sure it's always set.
            echo $x;
        }
    }
    
  2. Define a default value for the variable:

    function myFunction($a) {
        $x = ''; // Set a default which gets overridden for certain paths.
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        echo $x;
    }
    
  3. Add a value for the missing path:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
    
            // We add support for the missing case.
            default:
                $x = '';
                break;
        }
    
        echo $x;
    }
    
Loading history...
233
				Http::STATUS_INTERNAL_SERVER_ERROR
234
			);
235
		}
236
		return new JSONResponse(
237
			[],
238
			Http::STATUS_CREATED
239
		);
240
	}
241
242
	/**
243
	 * @param string $notificationType notification type (SHARE_REMOVED, etc)
244
	 * @param string $resourceType only 'file' is supported atm
245
	 * @param string $providerId Identifier of the resource at the provider side
246
	 * @param array $notification
247
	 * 		[
248
	 * 			optional additional parameters, depending on the notification
249
	 * 				and the resource type
250
	 * 		]
251
	 */
252
	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...
253
										$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...
254
										$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...
255
										$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...
256
	) {
257
		// TODO: implement
258
	}
259
260
	protected function getProtocols() {
261
		return [
262
			'webdav' => '/public.php/webdav/'
263
		];
264
	}
265
266
	/**
267
	 * Check if value is null or an array has any null item
268
	 *
269
	 * @param mixed $param
270
	 *
271
	 * @return bool
272
	 */
273 View Code Duplication
	protected function hasNull($param) {
274
		if (\is_array($param)) {
275
			return \in_array(null, $param, true);
276
		} else {
277
			return $param === null;
278
		}
279
	}
280
}
281