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

Jetpack_JSON_API_User_Create_Endpoint::result()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 2
nc 1
nop 0
dl 0
loc 3
rs 10
c 0
b 0
f 0
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