Completed
Push — content-options-blog-display-7... ( 930de1 )
by
unknown
12:25
created

Jetpack_JSON_API_User_Create_Endpoint   A

Complexity

Total Complexity 12

Size/Duplication

Total Lines 59
Duplicated Lines 15.25 %

Coupling/Cohesion

Components 1
Dependencies 2

Importance

Changes 0
Metric Value
dl 9
loc 59
rs 10
c 0
b 0
f 0
wmc 12
lcom 1
cbo 2

4 Methods

Rating   Name   Duplication   Size   Complexity  
A result() 0 3 1
A validate_input() 0 13 4
A create_or_get_user() 0 23 3
A get_user() 9 9 4

How to fix   Duplicated Code   

Duplicated Code

Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.

Common duplication problems, and corresponding solutions are:

1
<?php
2
3
class Jetpack_JSON_API_User_Create_Endpoint extends Jetpack_JSON_API_Endpoint {
4
5
	protected $needed_capabilities = 'create_users';
6
7
	private $user_data;
8
9
	function result() {
10
		return $this->create_or_get_user();
11
	}
12
13
	function validate_input( $object ) {
14
		$this->user_data = $this->input();
15
		if ( empty( $this->user_data ) ) {
16
			return new WP_Error( 'input_error', __( 'user_data is required', 'jetpack' ) );
17
		}
18
		if ( ! isset( $this->user_data[ 'email' ] ) ) {
19
			return new WP_Error( 'input_error', __( 'user email is required', 'jetpack' ) );
20
		}
21
		if ( ! isset( $this->user_data[ 'login' ] ) ) {
22
			return new WP_Error( 'input_error', __( 'user login is required', 'jetpack' ) );
23
		}
24
		return parent::validate_input( $object );
25
	}
26
27
	function create_or_get_user() {
28
		require_once JETPACK__PLUGIN_DIR . 'modules/sso/class.jetpack-sso-helpers.php';
29
30
		// Check for an existing user
31
		$user = get_user_by( 'email', $this->user_data['email'] );
32
33
		if ( ! $user ) {
34
			// We modify the input here to mimick the same call structure of the update user endpoint.
35
			$this->user_data = (object) $this->user_data;
36
			$roles = (array) $this->user_data->roles;
37
			$this->user_data->role = array_pop( $roles );
38
			$this->user_data->url = $this->user_data->roles;
39
			$this->user_data->display_name = $this->user_data->name;
40
			$this->user_data->description = '';
41
			$user = Jetpack_SSO_Helpers::generate_user( $this->user_data );
42
		}
43
44
		if ( ! $user ) {
45
			return false;
46
		}
47
48
		return $this->get_user( $user->ID );
49
	}
50
51 View Code Duplication
	public function get_user( $user_id ) {
52
		$the_user = $this->get_author( $user_id, true );
53
		if ( $the_user && ! is_wp_error( $the_user ) ) {
54
			$userdata = get_userdata( $user_id );
55
			$the_user->roles = ! is_wp_error( $userdata ) ? $userdata->roles : array();
56
		}
57
58
		return $the_user;
59
	}
60
61
}
62