Completed
Push — branch-4.9-pressable-built ( 58b565 )
by
unknown
24:04 queued 14:30
created

Jetpack_JSON_API_User_Create_Endpoint   A

Complexity

Total Complexity 12

Size/Duplication

Total Lines 60
Duplicated Lines 15 %

Coupling/Cohesion

Components 1
Dependencies 2

Importance

Changes 0
Metric Value
dl 9
loc 60
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
B create_or_get_user() 0 24 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
36
			$this->user_data = (object) $this->user_data;
37
			$roles = (array) $this->user_data->roles;
38
			$this->user_data->role = array_pop( $roles );
39
			$this->user_data->url = $this->user_data->roles;
40
			$this->user_data->display_name = $this->user_data->name;
41
			$this->user_data->description = '';
42
			$user = Jetpack_SSO_Helpers::generate_user( $this->user_data );
43
		}
44
45
		if ( ! $user ) {
46
			return false;
47
		}
48
49
		return $this->get_user( $user->ID );
50
	}
51
52 View Code Duplication
	public function get_user( $user_id ) {
53
		$the_user = $this->get_author( $user_id, true );
54
		if ( $the_user && ! is_wp_error( $the_user ) ) {
55
			$userdata = get_userdata( $user_id );
56
			$the_user->roles = ! is_wp_error( $userdata ) ? $userdata->roles : array();
57
		}
58
59
		return $the_user;
60
	}
61
62
}
63