Completed
Push — master ( 9458ed...7d322b )
by Henry
10:04
created

User::_validatePost()   C

Complexity

Conditions 12
Paths 84

Size

Total Lines 52

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 26
CRAP Score 12

Importance

Changes 0
Metric Value
dl 0
loc 52
ccs 26
cts 26
cp 1
rs 6.9666
c 0
b 0
f 0
cc 12
nc 84
nop 1
crap 12

How to fix   Long Method    Complexity   

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
namespace Redaxscript\Admin\Controller;
3
4
use Redaxscript\Admin;
5
use Redaxscript\Auth;
6
use Redaxscript\Filter;
7
use Redaxscript\Hash;
8
use Redaxscript\Validator;
9
use function json_encode;
10
11
/**
12
 * children class to process the admin user request
13
 *
14
 * @since 4.0.0
15
 *
16
 * @package Redaxscript
17
 * @category Controller
18
 * @author Henry Ruhs
19
 */
20
21
class User extends ControllerAbstract
22
{
23
	/**
24
	 * process the class
25
	 *
26
	 * @since 4.0.0
27
	 *
28
	 * @param string $action action to process
29
	 *
30
	 * @return string
31
	 */
32
33 14
	public function process(string $action = null) : string
34
	{
35 14
		$postArray = $this->_normalizePost($this->_sanitizePost());
36 14
		$validateArray = $this->_validatePost($postArray);
0 ignored issues
show
Bug introduced by Henry Ruhs
It seems like $postArray defined by $this->_normalizePost($this->_sanitizePost()) on line 35 can also be of type null; however, Redaxscript\Admin\Controller\User::_validatePost() does only seem to accept array, maybe add an additional type check?

If a method or function can return multiple different values and unless you are sure that you only can receive a single value in this context, we recommend to add an additional type check:

/**
 * @return array|string
 */
function returnsDifferentValues($x) {
    if ($x) {
        return 'foo';
    }

    return array();
}

$x = returnsDifferentValues($y);
if (is_array($x)) {
    // $x is an array.
}

If this a common case that PHP Analyzer should handle natively, please let us know by opening an issue.

Loading history...
37 14
		$passwordHash = new Hash();
38 14
		$myId = (int)$this->_registry->get('myId');
39
40
		/* validate post */
41
42 14
		if ($validateArray)
0 ignored issues
show
Bug Best Practice introduced by redaxmedia
The expression $validateArray of type array is implicitly converted to a boolean; are you sure this is intended? If so, consider using ! empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
43
		{
44 10
			return $this->_error(
45
			[
46 10
				'route' => $this->_getErrorRoute($postArray),
0 ignored issues
show
Bug introduced by redaxmedia
It seems like $postArray defined by $this->_normalizePost($this->_sanitizePost()) on line 35 can also be of type null; however, Redaxscript\Admin\Contro...\User::_getErrorRoute() does only seem to accept array, maybe add an additional type check?

If a method or function can return multiple different values and unless you are sure that you only can receive a single value in this context, we recommend to add an additional type check:

/**
 * @return array|string
 */
function returnsDifferentValues($x) {
    if ($x) {
        return 'foo';
    }

    return array();
}

$x = returnsDifferentValues($y);
if (is_array($x)) {
    // $x is an array.
}

If this a common case that PHP Analyzer should handle natively, please let us know by opening an issue.

Loading history...
47 10
				'message' => $validateArray
48
			]);
49
		}
50
51
		/* handle create */
52
53 4
		if ($action === 'create')
54
		{
55 1
			$passwordHash->init($postArray['password']);
56
			$createArray =
57
			[
58 1
				'name' => $postArray['name'],
59 1
				'user' => $postArray['user'],
60 1
				'description' => $postArray['description'],
61 1
				'password' => $passwordHash->getHash(),
62 1
				'email' => $postArray['email'],
63 1
				'language' => $postArray['language'],
64 1
				'status' => $postArray['status'],
65 1
				'groups' => $postArray['groups']
66
			];
67 1
			if ($this->_create($createArray))
68
			{
69 1
				return $this->_success(
70
				[
71 1
					'route' => $this->_getSuccessRoute($postArray),
72 1
					'timeout' => 2
73
				]);
74
			}
75
		}
76
77
		/* handle update */
78
79 3
		if ($action === 'update')
80
		{
81
			$updateFullArray =
82
			[
83 2
				'name' => $postArray['name'],
84 2
				'description' => $postArray['description'],
85 2
				'email' => $postArray['email'],
86 2
				'language' => $postArray['language'],
87 2
				'status' => $postArray['status'],
88 2
				'groups' => $postArray['groups']
89
			];
90
			$updateLiteArray =
91
			[
92 2
				'name' => $postArray['name'],
93 2
				'description' => $postArray['description'],
94 2
				'email' => $postArray['email'],
95 2
				'language' => $postArray['language']
96
			];
97 2
			if ($postArray['password'])
98
			{
99 2
				$passwordHash->init($postArray['password']);
100 2
				$updateFullArray['password'] = $updateLiteArray['password'] = $passwordHash->getHash();
101
			}
102 2
			if ($this->_update($postArray['id'], $postArray['id'] > 1 ? $updateFullArray : $updateLiteArray))
103
			{
104 2
				if ($postArray['id'] === $myId)
105
				{
106 2
					$this->_refresh($postArray);
107
				}
108 2
				return $this->_success(
109
				[
110 2
					'route' => $this->_getSuccessRoute($postArray),
111 2
					'timeout' => 2
112
				]);
113
			}
114
		}
115
116
		/* handle error */
117
118 1
		return $this->_error(
119
		[
120 1
			'route' => $this->_getErrorRoute($postArray)
0 ignored issues
show
Bug introduced by redaxmedia
It seems like $postArray defined by $this->_normalizePost($this->_sanitizePost()) on line 35 can also be of type null; however, Redaxscript\Admin\Contro...\User::_getErrorRoute() does only seem to accept array, maybe add an additional type check?

If a method or function can return multiple different values and unless you are sure that you only can receive a single value in this context, we recommend to add an additional type check:

/**
 * @return array|string
 */
function returnsDifferentValues($x) {
    if ($x) {
        return 'foo';
    }

    return array();
}

$x = returnsDifferentValues($y);
if (is_array($x)) {
    // $x is an array.
}

If this a common case that PHP Analyzer should handle natively, please let us know by opening an issue.

Loading history...
121
		]);
122
	}
123
124
	/**
125
	 * sanitize the post
126
	 *
127
	 * @since 4.0.0
128
	 *
129
	 * @return array
130
	 */
131
132 14
	protected function _sanitizePost() : array
133
	{
134 14
		$emailFilter = new Filter\Email();
135 14
		$numberFilter = new Filter\Number();
136 14
		$nameFilter = new Filter\Name();
137 14
		$toggleFilter = new Filter\Toggle();
138
		$specialFilter = new Filter\Special();
139
140
		/* sanitize post */
141
142
		return
143 14
		[
144 14
			'id' => $numberFilter->sanitize($this->_request->getPost('id')),
0 ignored issues
show
Bug introduced by redaxmedia
It seems like $this->_request->getPost('id') targeting Redaxscript\Request::getPost() can also be of type array; however, Redaxscript\Filter\Number::sanitize() does only seem to accept null|string, maybe add an additional type check?

This check looks at variables that are passed out again to other methods.

If the outgoing method call has stricter type requirements than the method itself, an issue is raised.

An additional type check may prevent trouble.

Loading history...
145 14
			'name' => $nameFilter->sanitize($this->_request->getPost('name')),
0 ignored issues
show
Bug introduced by redaxmedia
It seems like $this->_request->getPost('name') targeting Redaxscript\Request::getPost() can also be of type array; however, Redaxscript\Filter\Name::sanitize() does only seem to accept null|string, maybe add an additional type check?

This check looks at variables that are passed out again to other methods.

If the outgoing method call has stricter type requirements than the method itself, an issue is raised.

An additional type check may prevent trouble.

Loading history...
146 14
			'user' => $this->_request->getPost('user'),
147 14
			'description' => $this->_request->getPost('description'),
148 14
			'password' => $this->_request->getPost('password'),
149 14
			'email' => $emailFilter->sanitize($this->_request->getPost('email')),
0 ignored issues
show
Bug introduced by Henry Ruhs
It seems like $this->_request->getPost('email') targeting Redaxscript\Request::getPost() can also be of type array; however, Redaxscript\Filter\Email::sanitize() does only seem to accept null|string, maybe add an additional type check?

This check looks at variables that are passed out again to other methods.

If the outgoing method call has stricter type requirements than the method itself, an issue is raised.

An additional type check may prevent trouble.

Loading history...
150 14
			'language' => $specialFilter->sanitize($this->_request->getPost('language')),
0 ignored issues
show
Bug introduced by Henry Ruhs
It seems like $this->_request->getPost('language') targeting Redaxscript\Request::getPost() can also be of type array; however, Redaxscript\Filter\Special::sanitize() does only seem to accept null|string, maybe add an additional type check?

This check looks at variables that are passed out again to other methods.

If the outgoing method call has stricter type requirements than the method itself, an issue is raised.

An additional type check may prevent trouble.

Loading history...
151 14
			'status' => $toggleFilter->sanitize($this->_request->getPost('status')),
0 ignored issues
show
Bug introduced by redaxmedia
It seems like $this->_request->getPost('status') targeting Redaxscript\Request::getPost() can also be of type array; however, Redaxscript\Filter\Toggle::sanitize() does only seem to accept null|string, maybe add an additional type check?

This check looks at variables that are passed out again to other methods.

If the outgoing method call has stricter type requirements than the method itself, an issue is raised.

An additional type check may prevent trouble.

Loading history...
152 14
			'groups' => json_encode($this->_request->getPost('groups'))
153
		];
154
	}
155
156
	/**
157
	 * validate the post
158
	 *
159
	 * @since 4.0.0
160
	 *
161
	 * @param array $postArray array of the post
162
	 *
163
	 * @return array
164
	 */
165
166 14
	protected function _validatePost(array $postArray = []) : array
167
	{
168 14
		$nameValidator = new Validator\Name();
169 14
		$userValidator = new Validator\User();
170 14
		$passwordValidator = new Validator\Password();
171 14
		$emailValidator = new Validator\Email();
172 14
		$userModel = new Admin\Model\User();
173
		$validateArray = [];
174
175
		/* validate post */
176 14
177
		if (!$postArray['name'])
178 10
		{
179
			$validateArray[] = $this->_language->get('name_empty');
180 14
		}
181
		else if (!$nameValidator->validate($postArray['name']))
182 9
		{
183
			$validateArray[] = $this->_language->get('name_incorrect');
184 5
		}
185
		if (!$postArray['id'])
186 4
		{
187
			if (!$postArray['user'])
188 1
			{
189
				$validateArray[] = $this->_language->get('user_empty');
190 3
			}
191
			else if (!$userValidator->validate($postArray['user']))
192 1
			{
193
				$validateArray[] = $this->_language->get('user_incorrect');
194 9
			}
195
			else if ($userModel->getByUser($postArray['user']))
196 5
			{
197
				$validateArray[] = $this->_language->get('user_exists');
198 4
			}
199
			if (!$postArray['password'])
200 1
			{
201
				$validateArray[] = $this->_language->get('password_empty');
202 3
			}
203
			else if (!$passwordValidator->validate($postArray['password']))
204 9
			{
205
				$validateArray[] = $this->_language->get('password_incorrect');
206
			}
207 5
		}
208
		else if ($postArray['password'] && !$passwordValidator->validate($postArray['password']))
209 4
		{
210
			$validateArray[] = $this->_language->get('password_incorrect');
211 1
		}
212
		if (!$emailValidator->validate($postArray['email']))
213 3
		{
214
			$validateArray[] = $this->_language->get('email_incorrect');
215 1
		}
216
		return $validateArray;
217
	}
218 14
219
	/**
220 10
	 * create the user
221
	 *
222 14
	 * @since 4.0.0
223
	 *
224
	 * @param array $createArray array of the create
225
	 *
226
	 * @return bool
227
	 */
228
229
	protected function _create(array $createArray = []) : bool
230
	{
231
		$userModel = new Admin\Model\User();
232
		return $userModel->createByArray($createArray);
233
	}
234
235 1
	/**
236
	 * update the user
237 1
	 *
238 1
	 * @since 4.0.0
239
	 *
240
	 * @param int $userId identifier of the user
241
	 * @param array $updateArray array of the update
242
	 *
243
	 * @return bool
244
	 */
245
246
	protected function _update(int $userId = null, array $updateArray = []) : bool
247
	{
248
		$userModel = new Admin\Model\User();
249
		return $userModel->updateByIdAndArray($userId, $updateArray);
250
	}
251
252 2
	/**
253
	 * refresh the auth
254 2
	 *
255 2
	 * @since 4.0.0
256
	 *
257
	 * @param array $refreshArray array of the update
258
	 */
259
260
	protected function _refresh(array $refreshArray = []) : void
261
	{
262
		$auth = new Auth($this->_request);
263
		$auth->init();
264
		$auth->setUser('name', $refreshArray['name']);
265
		$auth->setUser('email', $refreshArray['email']);
266 2
		$auth->setUser('language', $refreshArray['language']);
267
		$auth->save();
268 2
	}
269 2
270 2
	/**
271 2
	 * get success route
272 2
	 *
273 2
	 * @since 4.0.0
274 2
	 *
275
	 * @param array $postArray array of the post
276
	 *
277
	 * @return string
278
	 */
279
280
	protected function _getSuccessRoute(array $postArray = []) : string
281
	{
282
		if ($this->_registry->get('usersEdit') && $postArray['id'])
283
		{
284
			return 'admin/view/users#row-' . $postArray['id'];
285
		}
286 3
		if ($this->_registry->get('usersEdit') && $postArray['user'])
287
		{
288 3
			$userModel = new Admin\Model\User();
289
			return 'admin/view/users#row-' . $userModel->getByUser($postArray['user'])->id;
290 1
		}
291
		return 'admin';
292 2
	}
293
294 1
	/**
295 1
	 * get error route
296
	 *
297 1
	 * @since 4.0.0
298
	 *
299
	 * @param array $postArray array of the post
300
	 *
301
	 * @return string
302
	 */
303
304
	protected function _getErrorRoute(array $postArray = []) : string
305
	{
306
		if ($this->_registry->get('usersEdit') && $postArray['id'])
307
		{
308
			return 'admin/edit/users/' . $postArray['id'];
309
		}
310 11
		if ($this->_registry->get('usersNew'))
311
		{
312 11
			return 'admin/new/users';
313
		}
314 1
		return 'admin';
315
	}
316
}
317