| Conditions | 17 |
| Paths | 28 |
| Total Lines | 44 |
| Code Lines | 31 |
| Lines | 0 |
| Ratio | 0 % |
| Changes | 1 | ||
| Bugs | 0 | Features | 0 |
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:
If many parameters/temporary variables are present:
| 1 | <?php |
||
| 69 | public function update_user( $user_id, $blog_id ) { |
||
| 70 | $input = $this->input(); |
||
| 71 | $user['ID'] = $user_id; |
||
|
|
|||
| 72 | $is_wpcom = defined( 'IS_WPCOM' ) && IS_WPCOM; |
||
| 73 | |||
| 74 | if ( get_current_user_id() == $user_id && isset( $input['roles'] ) ) { |
||
| 75 | return new WP_Error( 'unauthorized', 'You cannot change your own role', 403 ); |
||
| 76 | } |
||
| 77 | |||
| 78 | if ( $is_wpcom && $user_id !== get_current_user_id() && $user_id == wpcom_get_blog_owner( $blog_id ) ) { |
||
| 79 | return new WP_Error( 'unauthorized_edit_owner', 'Current user can not edit blog owner', 403 ); |
||
| 80 | } |
||
| 81 | |||
| 82 | if ( ! $is_wpcom ) { |
||
| 83 | foreach ( $input as $key => $value ) { |
||
| 84 | if ( ! is_array( $value ) ) { |
||
| 85 | $value = trim( $value ); |
||
| 86 | } |
||
| 87 | $value = wp_unslash( $value ); |
||
| 88 | switch ( $key ) { |
||
| 89 | case 'first_name': |
||
| 90 | case 'last_name': |
||
| 91 | $user[ $key ] = $value; |
||
| 92 | break; |
||
| 93 | case 'display_name': |
||
| 94 | case 'name': |
||
| 95 | $user[ 'display_name' ] = $value; |
||
| 96 | break; |
||
| 97 | } |
||
| 98 | } |
||
| 99 | } |
||
| 100 | if ( isset( $input[ 'roles' ] ) ) { |
||
| 101 | if ( is_array( $input['roles'] ) ) { |
||
| 102 | $user['role'] = $input['roles'][0]; |
||
| 103 | } else { |
||
| 104 | $user['role'] = $input['roles']; |
||
| 105 | } |
||
| 106 | } |
||
| 107 | $result = wp_update_user( $user ); |
||
| 108 | if ( is_wp_error( $result ) ) { |
||
| 109 | return $result; |
||
| 110 | } |
||
| 111 | return $this->get_user( $user_id ); |
||
| 112 | } |
||
| 113 | |||
| 115 |
Adding an explicit array definition is generally preferable to implicit array definition as it guarantees a stable state of the code.
Let’s take a look at an example:
As you can see in this example, the array
$myArrayis initialized the first time when the foreach loop is entered. You can also see that the value of thebarkey is only written conditionally; thus, its value might result from a previous iteration.This might or might not be intended. To make your intention clear, your code more readible and to avoid accidental bugs, we recommend to add an explicit initialization $myArray = array() either outside or inside the foreach loop.