Completed
Push — master ( 89b6ee...61842f )
by Morris
34:27 queued 17:16
created

PersonalInfo::getForm()   B

Complexity

Conditions 3
Paths 4

Size

Total Lines 55

Duplication

Lines 5
Ratio 9.09 %

Importance

Changes 0
Metric Value
cc 3
nc 4
nop 0
dl 5
loc 55
rs 8.9818
c 0
b 0
f 0

How to fix   Long Method   

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:

1
<?php
2
/**
3
 * @copyright Copyright (c) 2017 Arthur Schiwon <[email protected]>
4
 *
5
 * @author Arthur Schiwon <[email protected]>
6
 * @author Morris Jobke <[email protected]>
7
 * @author Thomas Citharel <[email protected]>
8
 *
9
 * @license GNU AGPL version 3 or any later version
10
 *
11
 * This program is free software: you can redistribute it and/or modify
12
 * it under the terms of the GNU Affero General Public License as
13
 * published by the Free Software Foundation, either version 3 of the
14
 * License, or (at your option) any later version.
15
 *
16
 * This program is distributed in the hope that it will be useful,
17
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
18
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
19
 * GNU Affero General Public License for more details.
20
 *
21
 * You should have received a copy of the GNU Affero General Public License
22
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
23
 *
24
 */
25
26
namespace OC\Settings\Personal;
27
28
use OC\Accounts\AccountManager;
29
use OCA\FederatedFileSharing\AppInfo\Application;
30
use OCP\App\IAppManager;
31
use OCP\AppFramework\Http\TemplateResponse;
32
use OCP\Files\FileInfo;
33
use OCP\IConfig;
34
use OCP\IGroup;
35
use OCP\IGroupManager;
36
use OCP\IL10N;
37
use OCP\IUser;
38
use OCP\IUserManager;
39
use OCP\L10N\IFactory;
40
use OCP\Settings\ISettings;
41
42
class PersonalInfo implements ISettings {
43
44
	/** @var IConfig */
45
	private $config;
46
	/** @var IUserManager */
47
	private $userManager;
48
	/** @var AccountManager */
49
	private $accountManager;
50
	/** @var IGroupManager */
51
	private $groupManager;
52
	/** @var IAppManager */
53
	private $appManager;
54
	/** @var IFactory */
55
	private $l10nFactory;
56
	/** @var IL10N */
57
	private $l;
58
59
	/**
60
	 * @param IConfig $config
61
	 * @param IUserManager $userManager
62
	 * @param IGroupManager $groupManager
63
	 * @param AccountManager $accountManager
64
	 * @param IFactory $l10nFactory
65
	 * @param IL10N $l
66
	 */
67
	public function __construct(
68
		IConfig $config,
69
		IUserManager $userManager,
70
		IGroupManager $groupManager,
71
		AccountManager $accountManager,
72
		IAppManager $appManager,
73
		IFactory $l10nFactory,
74
		IL10N $l
75
	) {
76
		$this->config = $config;
77
		$this->userManager = $userManager;
78
		$this->accountManager = $accountManager;
79
		$this->groupManager = $groupManager;
80
		$this->appManager = $appManager;
81
		$this->l10nFactory = $l10nFactory;
82
		$this->l = $l;
83
	}
84
85
	/**
86
	 * @return TemplateResponse returns the instance with all parameters set, ready to be rendered
87
	 * @since 9.1
88
	 */
89
	public function getForm() {
90
		$federatedFileSharingEnabled = $this->appManager->isEnabledForUser('federatedfilesharing');
91
		$lookupServerUploadEnabled = false;
92
		if($federatedFileSharingEnabled) {
93
			$federatedFileSharing = new Application();
94
			$shareProvider = $federatedFileSharing->getFederatedShareProvider();
95
			$lookupServerUploadEnabled = $shareProvider->isLookupServerUploadEnabled();
96
		}
97
98
		$uid = \OC_User::getUser();
99
		$user = $this->userManager->get($uid);
100
		$userData = $this->accountManager->getUser($user);
0 ignored issues
show
Bug introduced by
It seems like $user defined by $this->userManager->get($uid) on line 99 can be null; however, OC\Accounts\AccountManager::getUser() does not accept null, maybe add an additional type check?

Unless you are absolutely sure that the expression can never be null because of other conditions, we strongly recommend to add an additional type check to your code:

/** @return stdClass|null */
function mayReturnNull() { }

function doesNotAcceptNull(stdClass $x) { }

// With potential error.
function withoutCheck() {
    $x = mayReturnNull();
    doesNotAcceptNull($x); // Potential error here.
}

// Safe - Alternative 1
function withCheck1() {
    $x = mayReturnNull();
    if ( ! $x instanceof stdClass) {
        throw new \LogicException('$x must be defined.');
    }
    doesNotAcceptNull($x);
}

// Safe - Alternative 2
function withCheck2() {
    $x = mayReturnNull();
    if ($x instanceof stdClass) {
        doesNotAcceptNull($x);
    }
}
Loading history...
101
102
		$storageInfo = \OC_Helper::getStorageInfo('/');
103 View Code Duplication
		if ($storageInfo['quota'] === FileInfo::SPACE_UNLIMITED) {
104
			$totalSpace = $this->l->t('Unlimited');
105
		} else {
106
			$totalSpace = \OC_Helper::humanFileSize($storageInfo['total']);
107
		}
108
109
		$languageParameters = $this->getLanguages($user);
0 ignored issues
show
Bug introduced by
It seems like $user defined by $this->userManager->get($uid) on line 99 can be null; however, OC\Settings\Personal\PersonalInfo::getLanguages() does not accept null, maybe add an additional type check?

Unless you are absolutely sure that the expression can never be null because of other conditions, we strongly recommend to add an additional type check to your code:

/** @return stdClass|null */
function mayReturnNull() { }

function doesNotAcceptNull(stdClass $x) { }

// With potential error.
function withoutCheck() {
    $x = mayReturnNull();
    doesNotAcceptNull($x); // Potential error here.
}

// Safe - Alternative 1
function withCheck1() {
    $x = mayReturnNull();
    if ( ! $x instanceof stdClass) {
        throw new \LogicException('$x must be defined.');
    }
    doesNotAcceptNull($x);
}

// Safe - Alternative 2
function withCheck2() {
    $x = mayReturnNull();
    if ($x instanceof stdClass) {
        doesNotAcceptNull($x);
    }
}
Loading history...
110
		$localeParameters = $this->getLocales($user);
0 ignored issues
show
Bug introduced by
It seems like $user defined by $this->userManager->get($uid) on line 99 can be null; however, OC\Settings\Personal\PersonalInfo::getLocales() does not accept null, maybe add an additional type check?

Unless you are absolutely sure that the expression can never be null because of other conditions, we strongly recommend to add an additional type check to your code:

/** @return stdClass|null */
function mayReturnNull() { }

function doesNotAcceptNull(stdClass $x) { }

// With potential error.
function withoutCheck() {
    $x = mayReturnNull();
    doesNotAcceptNull($x); // Potential error here.
}

// Safe - Alternative 1
function withCheck1() {
    $x = mayReturnNull();
    if ( ! $x instanceof stdClass) {
        throw new \LogicException('$x must be defined.');
    }
    doesNotAcceptNull($x);
}

// Safe - Alternative 2
function withCheck2() {
    $x = mayReturnNull();
    if ($x instanceof stdClass) {
        doesNotAcceptNull($x);
    }
}
Loading history...
111
		$messageParameters = $this->getMessageParameters($userData);
112
113
		$parameters = [
114
			'total_space' => $totalSpace,
115
			'usage' => \OC_Helper::humanFileSize($storageInfo['used']),
116
			'usage_relative' => round($storageInfo['relative']),
117
			'quota' => $storageInfo['quota'],
118
			'avatarChangeSupported' => $user->canChangeAvatar(),
119
			'lookupServerUploadEnabled' => $lookupServerUploadEnabled,
120
			'avatarScope' => $userData[AccountManager::PROPERTY_AVATAR]['scope'],
121
			'displayNameChangeSupported' => $user->canChangeDisplayName(),
122
			'displayName' => $userData[AccountManager::PROPERTY_DISPLAYNAME]['value'],
123
			'displayNameScope' => $userData[AccountManager::PROPERTY_DISPLAYNAME]['scope'],
124
			'email' => $userData[AccountManager::PROPERTY_EMAIL]['value'],
125
			'emailScope' => $userData[AccountManager::PROPERTY_EMAIL]['scope'],
126
			'emailVerification' => $userData[AccountManager::PROPERTY_EMAIL]['verified'],
127
			'phone' => $userData[AccountManager::PROPERTY_PHONE]['value'],
128
			'phoneScope' => $userData[AccountManager::PROPERTY_PHONE]['scope'],
129
			'address' => $userData[AccountManager::PROPERTY_ADDRESS]['value'],
130
			'addressScope' => $userData[AccountManager::PROPERTY_ADDRESS]['scope'],
131
			'website' =>  $userData[AccountManager::PROPERTY_WEBSITE]['value'],
132
			'websiteScope' =>  $userData[AccountManager::PROPERTY_WEBSITE]['scope'],
133
			'websiteVerification' => $userData[AccountManager::PROPERTY_WEBSITE]['verified'],
134
			'twitter' => $userData[AccountManager::PROPERTY_TWITTER]['value'],
135
			'twitterScope' => $userData[AccountManager::PROPERTY_TWITTER]['scope'],
136
			'twitterVerification' => $userData[AccountManager::PROPERTY_TWITTER]['verified'],
137
			'groups' => $this->getGroups($user),
0 ignored issues
show
Bug introduced by
It seems like $user defined by $this->userManager->get($uid) on line 99 can be null; however, OC\Settings\Personal\PersonalInfo::getGroups() does not accept null, maybe add an additional type check?

Unless you are absolutely sure that the expression can never be null because of other conditions, we strongly recommend to add an additional type check to your code:

/** @return stdClass|null */
function mayReturnNull() { }

function doesNotAcceptNull(stdClass $x) { }

// With potential error.
function withoutCheck() {
    $x = mayReturnNull();
    doesNotAcceptNull($x); // Potential error here.
}

// Safe - Alternative 1
function withCheck1() {
    $x = mayReturnNull();
    if ( ! $x instanceof stdClass) {
        throw new \LogicException('$x must be defined.');
    }
    doesNotAcceptNull($x);
}

// Safe - Alternative 2
function withCheck2() {
    $x = mayReturnNull();
    if ($x instanceof stdClass) {
        doesNotAcceptNull($x);
    }
}
Loading history...
138
			'passwordChangeSupported' => $user->canChangePassword(),
139
		] + $messageParameters + $languageParameters + $localeParameters;
140
141
142
		return new TemplateResponse('settings', 'settings/personal/personal.info', $parameters, '');
143
	}
144
145
	/**
146
	 * @return string the section ID, e.g. 'sharing'
147
	 * @since 9.1
148
	 */
149
	public function getSection() {
150
		return 'personal-info';
151
	}
152
153
	/**
154
	 * @return int whether the form should be rather on the top or bottom of
155
	 * the admin section. The forms are arranged in ascending order of the
156
	 * priority values. It is required to return a value between 0 and 100.
157
	 *
158
	 * E.g.: 70
159
	 * @since 9.1
160
	 */
161
	public function getPriority() {
162
		return 10;
163
	}
164
165
	/**
166
	 * returns a sorted list of the user's group GIDs
167
	 *
168
	 * @param IUser $user
169
	 * @return array
170
	 */
171
	private function getGroups(IUser $user) {
172
		$groups = array_map(
173
			function(IGroup $group) {
174
				return $group->getDisplayName();
175
			},
176
			$this->groupManager->getUserGroups($user)
177
		);
178
		sort($groups);
179
180
		return $groups;
181
	}
182
183
	/**
184
	 * returns the user language, common language and other languages in an
185
	 * associative array
186
	 *
187
	 * @param IUser $user
188
	 * @return array
189
	 */
190
	private function getLanguages(IUser $user) {
191
		$forceLanguage = $this->config->getSystemValue('force_language', false);
192
		if($forceLanguage !== false) {
193
			return [];
194
		}
195
196
		$uid = $user->getUID();
197
198
		$userConfLang = $this->config->getUserValue($uid, 'core', 'lang', $this->l10nFactory->findLanguage());
199
		$languages = $this->l10nFactory->getLanguages();
200
201
		// associate the user language with the proper array
202
		$userLangIndex = array_search($userConfLang, array_column($languages['commonlanguages'], 'code'));
203
		$userLang = $languages['commonlanguages'][$userLangIndex];
204
		// search in the other languages
205
		if ($userLangIndex === false) {
206
			$userLangIndex = array_search($userConfLang, array_column($languages['languages'], 'code'));		
207
			$userLang = $languages['languages'][$userLangIndex];
208
		}
209
		// if user language is not available but set somehow: show the actual code as name
210
		if (!is_array($userLang)) {
211
			$userLang = [
212
				'code' => $userConfLang,
213
				'name' => $userConfLang,
214
			];
215
		}
216
217
		return array_merge(
218
			array('activelanguage' => $userLang),
219
			$languages
220
		);
221
	}
222
223
	private function getLocales(IUser $user) {
224
		$forceLanguage = $this->config->getSystemValue('force_locale', false);
225
		if($forceLanguage !== false) {
226
			return [];
227
		}
228
229
		$uid = $user->getUID();
230
231
		$userLocaleString = $this->config->getUserValue($uid, 'core', 'locale', 'en_US');
232
233
		$userLang = $this->config->getUserValue($uid, 'core', 'lang', $this->l10nFactory->findLanguage());
234
235
		$localeCodes = $this->l10nFactory->findAvailableLocales();
236
237
		$userLocale = array_filter($localeCodes, function($value) use ($userLocaleString) {
238
			return $userLocaleString === $value['code'];
239
		});
240
241
		if (!empty($userLocale))
242
		{
243
			$userLocale = reset($userLocale);
244
		}
245
246
		$localesForLanguage = array_filter($localeCodes, function($localeCode) use ($userLang) {
247
			return 0 === strpos($localeCode['code'], $userLang);
248
		});
249
250
		return [
251
			'activelocaleLang' => $userLocaleString,
252
			'activelocale' => $userLocale,
253
			'locales' => $localeCodes,
254
			'localesForLanguage' => $localesForLanguage,
255
		];
256
	}
257
258
	/**
259
	 * @param array $userData
260
	 * @return array
261
	 */
262
	private function getMessageParameters(array $userData) {
263
		$needVerifyMessage = [AccountManager::PROPERTY_EMAIL, AccountManager::PROPERTY_WEBSITE, AccountManager::PROPERTY_TWITTER];
264
		$messageParameters = [];
265
		foreach ($needVerifyMessage as $property) {
266
			switch ($userData[$property]['verified']) {
267
				case AccountManager::VERIFIED:
268
					$message = $this->l->t('Verifying');
269
					break;
270
				case AccountManager::VERIFICATION_IN_PROGRESS:
271
					$message = $this->l->t('Verifying …');
272
					break;
273
				default:
274
					$message = $this->l->t('Verify');
275
			}
276
			$messageParameters[$property . 'Message'] = $message;
277
		}
278
		return $messageParameters;
279
	}
280
281
}
282