Completed
Push — master ( b59fdd...b18a22 )
by Henry
05:47
created

User::_validatePost()   B

Complexity

Conditions 11
Paths 56

Size

Total Lines 47

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 24
CRAP Score 11

Importance

Changes 0
Metric Value
dl 0
loc 47
ccs 24
cts 24
cp 1
rs 7.3166
c 0
b 0
f 0
cc 11
nc 56
nop 1
crap 11

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