Completed
Push — master ( b3c0be...0745f1 )
by Claudio
07:57
created

WC_REST_Customers_Controller::get_role_names()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 5
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
dl 0
loc 5
rs 9.4285
c 0
b 0
f 0
eloc 3
nc 1
nop 0
1
<?php
2
/**
3
 * REST API Customers controller
4
 *
5
 * Handles requests to the /customers endpoint.
6
 *
7
 * @author   WooThemes
8
 * @category API
9
 * @package  WooCommerce/API
10
 * @since    2.6.0
11
 */
12
13
if ( ! defined( 'ABSPATH' ) ) {
14
	exit;
15
}
16
17
/**
18
 * REST API Customers controller class.
19
 *
20
 * @package WooCommerce/API
21
 * @extends WC_REST_Controller
22
 */
23
class WC_REST_Customers_Controller extends WC_REST_Controller {
24
25
	/**
26
	 * Endpoint namespace.
27
	 *
28
	 * @var string
29
	 */
30
	protected $namespace = 'wc/v1';
31
32
	/**
33
	 * Route base.
34
	 *
35
	 * @var string
36
	 */
37
	protected $rest_base = 'customers';
38
39
	/**
40
	 * Register the routes for customers.
41
	 */
42
	public function register_routes() {
43
		register_rest_route( $this->namespace, '/' . $this->rest_base, array(
44
			array(
45
				'methods'             => WP_REST_Server::READABLE,
46
				'callback'            => array( $this, 'get_items' ),
47
				'permission_callback' => array( $this, 'get_items_permissions_check' ),
48
				'args'                => $this->get_collection_params(),
49
			),
50
			array(
51
				'methods'             => WP_REST_Server::CREATABLE,
52
				'callback'            => array( $this, 'create_item' ),
53
				'permission_callback' => array( $this, 'create_item_permissions_check' ),
54
				'args'                => array_merge( $this->get_endpoint_args_for_item_schema( WP_REST_Server::CREATABLE ), array(
55
					'email' => array(
56
						'required' => true,
57
					),
58
					'username' => array(
59
						'required' => 'no' === get_option( 'woocommerce_registration_generate_username', 'yes' ),
60
					),
61
					'password' => array(
62
						'required' => 'no' === get_option( 'woocommerce_registration_generate_password', 'no' ),
63
					),
64
				) ),
65
			),
66
			'schema' => array( $this, 'get_public_item_schema' ),
67
		) );
68
69
		register_rest_route( $this->namespace, '/' . $this->rest_base . '/(?P<id>[\d]+)', array(
70
			array(
71
				'methods'             => WP_REST_Server::READABLE,
72
				'callback'            => array( $this, 'get_item' ),
73
				'permission_callback' => array( $this, 'get_item_permissions_check' ),
74
				'args'                => array(
75
					'context' => $this->get_context_param( array( 'default' => 'view' ) ),
76
				),
77
			),
78
			array(
79
				'methods'             => WP_REST_Server::EDITABLE,
80
				'callback'            => array( $this, 'update_item' ),
81
				'permission_callback' => array( $this, 'update_item_permissions_check' ),
82
				'args'                => $this->get_endpoint_args_for_item_schema( WP_REST_Server::EDITABLE ),
83
			),
84
			array(
85
				'methods'             => WP_REST_Server::DELETABLE,
86
				'callback'            => array( $this, 'delete_item' ),
87
				'permission_callback' => array( $this, 'delete_item_permissions_check' ),
88
				'args'                => array(
89
					'force' => array(
90
						'default'     => false,
91
						'description' => __( 'Required to be true, as resource does not support trashing.', 'woocommerce' ),
92
					),
93
					'reassign' => array(),
94
				),
95
			),
96
			'schema' => array( $this, 'get_public_item_schema' ),
97
		) );
98
99
		register_rest_route( $this->namespace, '/' . $this->rest_base . '/batch', array(
100
			array(
101
				'methods'             => WP_REST_Server::EDITABLE,
102
				'callback'            => array( $this, 'batch_items' ),
103
				'permission_callback' => array( $this, 'batch_items_permissions_check' ),
104
				'args'                => $this->get_endpoint_args_for_item_schema( WP_REST_Server::EDITABLE ),
105
			),
106
			'schema' => array( $this, 'get_public_batch_schema' ),
107
		) );
108
	}
109
110
	/**
111
	 * Check whether a given request has permission to read customers.
112
	 *
113
	 * @param  WP_REST_Request $request Full details about the request.
114
	 * @return WP_Error|boolean
115
	 */
116 View Code Duplication
	public function get_items_permissions_check( $request ) {
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
117
		if ( ! wc_rest_check_user_permissions( 'read' ) ) {
118
			return new WP_Error( 'woocommerce_rest_cannot_view', __( 'Sorry, you cannot list resources.', 'woocommerce' ), array( 'status' => rest_authorization_required_code() ) );
119
		}
120
121
		return true;
122
	}
123
124
	/**
125
	 * Check if a given request has access create customers.
126
	 *
127
	 * @param  WP_REST_Request $request Full details about the request.
128
	 * @return boolean
129
	 */
130 View Code Duplication
	public function create_item_permissions_check( $request ) {
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
131
		if ( ! wc_rest_check_user_permissions( 'create' ) ) {
132
			return new WP_Error( 'woocommerce_rest_cannot_create', __( 'Sorry, you are not allowed to create resources.', 'woocommerce' ), array( 'status' => rest_authorization_required_code() ) );
133
		}
134
135
		return true;
136
	}
137
138
	/**
139
	 * Check if a given request has access to read a customer.
140
	 *
141
	 * @param  WP_REST_Request $request Full details about the request.
142
	 * @return WP_Error|boolean
143
	 */
144 View Code Duplication
	public function get_item_permissions_check( $request ) {
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
145
		$id = (int) $request['id'];
146
147
		if ( ! wc_rest_check_user_permissions( 'read', $id ) ) {
148
			return new WP_Error( 'woocommerce_rest_cannot_view', __( 'Sorry, you cannot view this resource.', 'woocommerce' ), array( 'status' => rest_authorization_required_code() ) );
149
		}
150
151
		return true;
152
	}
153
154
	/**
155
	 * Check if a given request has access update a customer.
156
	 *
157
	 * @param  WP_REST_Request $request Full details about the request.
158
	 * @return boolean
159
	 */
160 View Code Duplication
	public function update_item_permissions_check( $request ) {
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
161
		$id = (int) $request['id'];
162
163
		if ( ! wc_rest_check_user_permissions( 'edit', $id ) ) {
164
			return new WP_Error( 'woocommerce_rest_cannot_edit', __( 'Sorry, you are not allowed to edit this resource.', 'woocommerce' ), array( 'status' => rest_authorization_required_code() ) );
165
		}
166
167
		return true;
168
	}
169
170
	/**
171
	 * Check if a given request has access delete a customer.
172
	 *
173
	 * @param  WP_REST_Request $request Full details about the request.
174
	 * @return boolean
175
	 */
176 View Code Duplication
	public function delete_item_permissions_check( $request ) {
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
177
		$id = (int) $request['id'];
178
179
		if ( ! wc_rest_check_user_permissions( 'delete', $id ) ) {
180
			return new WP_Error( 'woocommerce_rest_cannot_delete', __( 'Sorry, you are not allowed to delete this resource.', 'woocommerce' ), array( 'status' => rest_authorization_required_code() ) );
181
		}
182
183
		return true;
184
	}
185
186
	/**
187
	 * Check if a given request has access batch create, update and delete items.
188
	 *
189
	 * @param  WP_REST_Request $request Full details about the request.
190
	 * @return boolean
191
	 */
192 View Code Duplication
	public function batch_items_permissions_check( $request ) {
0 ignored issues
show
Unused Code introduced by
The parameter $request is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
193
		if ( ! wc_rest_check_user_permissions( 'batch' ) ) {
194
			return new WP_Error( 'woocommerce_rest_cannot_batch', __( 'Sorry, you are not allowed to batch manipulate this resource.', 'woocommerce' ), array( 'status' => rest_authorization_required_code() ) );
195
		}
196
197
		return true;
198
	}
199
200
	/**
201
	 * Get all customers.
202
	 *
203
	 * @param WP_REST_Request $request Full details about the request.
204
	 * @return WP_Error|WP_REST_Response
205
	 */
206
	public function get_items( $request ) {
207
		$prepared_args = array();
208
		$prepared_args['exclude'] = $request['exclude'];
209
		$prepared_args['include'] = $request['include'];
210
		$prepared_args['order']   = $request['order'];
211
		$prepared_args['number']  = $request['per_page'];
212 View Code Duplication
		if ( ! empty( $request['offset'] ) ) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
213
			$prepared_args['offset'] = $request['offset'];
214
		} else {
215
			$prepared_args['offset'] = ( $request['page'] - 1 ) * $prepared_args['number'];
216
		}
217
		$orderby_possibles = array(
218
			'id'              => 'ID',
219
			'include'         => 'include',
220
			'name'            => 'display_name',
221
			'registered_date' => 'registered',
222
		);
223
		$prepared_args['orderby'] = $orderby_possibles[ $request['orderby'] ];
224
		$prepared_args['search']  = $request['search'];
225
226
		if ( '' !== $prepared_args['search'] ) {
227
			$prepared_args['search'] = '*' . $prepared_args['search'] . '*';
228
		}
229
230
		// Filter by email.
231
		if ( ! empty( $request['email'] ) ) {
232
			$prepared_args['search']         = $request['email'];
233
			$prepared_args['search_columns'] = array( 'user_email' );
234
		}
235
236
		// Filter by role.
237
		if ( 'all' !== $request['role'] ) {
238
			$prepared_args['role'] = $request['role'];
239
		}
240
241
		/**
242
		 * Filter arguments, before passing to WP_User_Query, when querying users via the REST API.
243
		 *
244
		 * @see https://developer.wordpress.org/reference/classes/wp_user_query/
245
		 *
246
		 * @param array           $prepared_args Array of arguments for WP_User_Query.
247
		 * @param WP_REST_Request $request       The current request.
248
		 */
249
		$prepared_args = apply_filters( 'woocommerce_rest_customer_query', $prepared_args, $request );
250
251
		$query = new WP_User_Query( $prepared_args );
252
253
		$users = array();
254
		foreach ( $query->results as $user ) {
255
			$data = $this->prepare_item_for_response( $user, $request );
256
			$users[] = $this->prepare_response_for_collection( $data );
257
		}
258
259
		$response = rest_ensure_response( $users );
260
261
		// Store pagation values for headers then unset for count query.
262
		$per_page = (int) $prepared_args['number'];
263
		$page = ceil( ( ( (int) $prepared_args['offset'] ) / $per_page ) + 1 );
264
265
		$prepared_args['fields'] = 'ID';
266
267
		$total_users = $query->get_total();
268
		if ( $total_users < 1 ) {
269
			// Out-of-bounds, run the query again without LIMIT for total count.
270
			unset( $prepared_args['number'] );
271
			unset( $prepared_args['offset'] );
272
			$count_query = new WP_User_Query( $prepared_args );
273
			$total_users = $count_query->get_total();
274
		}
275
		$response->header( 'X-WP-Total', (int) $total_users );
276
		$max_pages = ceil( $total_users / $per_page );
277
		$response->header( 'X-WP-TotalPages', (int) $max_pages );
278
279
		$base = add_query_arg( $request->get_query_params(), rest_url( sprintf( '/%s/%s', $this->namespace, $this->rest_base ) ) );
280 View Code Duplication
		if ( $page > 1 ) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
281
			$prev_page = $page - 1;
282
			if ( $prev_page > $max_pages ) {
283
				$prev_page = $max_pages;
284
			}
285
			$prev_link = add_query_arg( 'page', $prev_page, $base );
286
			$response->link_header( 'prev', $prev_link );
287
		}
288 View Code Duplication
		if ( $max_pages > $page ) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
289
			$next_page = $page + 1;
290
			$next_link = add_query_arg( 'page', $next_page, $base );
291
			$response->link_header( 'next', $next_link );
292
		}
293
294
		return $response;
295
	}
296
297
	/**
298
	 * Create a single customer.
299
	 *
300
	 * @param WP_REST_Request $request Full details about the request.
301
	 * @return WP_Error|WP_REST_Response
302
	 */
303
	public function create_item( $request ) {
304
		if ( ! empty( $request['id'] ) ) {
305
			return new WP_Error( 'woocommerce_rest_customer_exists', __( 'Cannot create existing resource.', 'woocommerce' ), array( 'status' => 400 ) );
306
		}
307
308
		// Sets the username.
309
		$request['username'] = ! empty( $request['username'] ) ? $request['username'] : '';
310
311
		// Sets the password.
312
		$request['password'] = ! empty( $request['password'] ) ? $request['password'] : '';
313
314
		// Create customer.
315
		$customer = new WC_Customer;
316
		$customer->set_username( $request['username'] );
317
		$customer->set_password( $request['password'] );
318
		$customer->set_email( $request['email'] );
319
		$customer->create();
320
321
		if ( ! $customer->get_id() ) {
322
			return new WP_Error( 'woocommerce_rest_cannot_create', __( 'This resource cannot be created.', 'woocommerce' ), array( 'status' => 400 ) );
323
		}
324
325
		$this->update_customer_meta_fields( $customer, $request );
326
		$customer->save();
327
328
		$user_data = get_user_by( 'id', $customer->get_id() );
329
		$this->update_additional_fields_for_object( $user_data, $request );
330
331
		/**
332
		 * Fires after a customer is created or updated via the REST API.
333
		 *
334
		 * @param WP_User         $user_data Data used to create the customer.
335
		 * @param WP_REST_Request $request   Request object.
336
		 * @param boolean         $creating  True when creating customer, false when updating customer.
337
		 */
338
		do_action( 'woocommerce_rest_insert_customer', $user_data, $request, true );
339
340
		$request->set_param( 'context', 'edit' );
341
		$response = $this->prepare_item_for_response( $user_data, $request );
342
		$response = rest_ensure_response( $response );
343
		$response->set_status( 201 );
344
		$response->header( 'Location', rest_url( sprintf( '/%s/%s/%d', $this->namespace, $this->rest_base, $customer->get_id() ) ) );
345
346
		return $response;
347
	}
348
349
	/**
350
	 * Get a single customer.
351
	 *
352
	 * @param WP_REST_Request $request Full details about the request.
353
	 * @return WP_Error|WP_REST_Response
354
	 */
355 View Code Duplication
	public function get_item( $request ) {
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
356
		$id        = (int) $request['id'];
357
		$user_data = get_userdata( $id );
358
359
		if ( empty( $id ) || empty( $user_data->ID ) ) {
360
			return new WP_Error( 'woocommerce_rest_invalid_id', __( 'Invalid resource ID.', 'woocommerce' ), array( 'status' => 404 ) );
361
		}
362
363
		$customer = $this->prepare_item_for_response( $user_data, $request );
364
		$response = rest_ensure_response( $customer );
365
366
		return $response;
367
	}
368
369
	/**
370
	 * Update a single user.
371
	 *
372
	 * @param WP_REST_Request $request Full details about the request.
373
	 * @return WP_Error|WP_REST_Response
374
	 */
375
	public function update_item( $request ) {
376
		$id       = (int) $request['id'];
377
		$customer = new WC_Customer( $id );
378
379
		if ( ! $customer->get_id() ) {
380
			return new WP_Error( 'woocommerce_rest_invalid_id', __( 'Invalid resource ID.', 'woocommerce' ), array( 'status' => 400 ) );
381
		}
382
383
		if ( ! empty( $request['email'] ) && email_exists( $request['email'] ) && $request['email'] !== $customer->get_email() ) {
384
			return new WP_Error( 'woocommerce_rest_customer_invalid_email', __( 'Email address is invalid.', 'woocommerce' ), array( 'status' => 400 ) );
385
		}
386
387
		if ( ! empty( $request['username'] ) && $request['username'] !== $customer->get_username() ) {
388
			return new WP_Error( 'woocommerce_rest_customer_invalid_argument', __( "Username isn't editable.", 'woocommerce' ), array( 'status' => 400 ) );
389
		}
390
391
		// Customer email.
392
		if ( isset( $request['email'] ) ) {
393
			$customer->set_email( sanitize_email( $request['email'] ) );
394
		}
395
396
		// Customer password.
397
		if ( isset( $request['password'] ) ) {
398
			$customer->set_password( wc_clean( $request['password'] ) );
399
		}
400
401
		$this->update_customer_meta_fields( $customer, $request );
402
		$customer->save();
403
404
		$user_data = get_userdata( $customer->get_id() );
405
		$this->update_additional_fields_for_object( $user_data, $request );
406
407
		/**
408
		 * Fires after a customer is created or updated via the REST API.
409
		 *
410
		 * @param WP_User         $customer  Data used to create the customer.
411
		 * @param WP_REST_Request $request   Request object.
412
		 * @param boolean         $creating  True when creating customer, false when updating customer.
413
		 */
414
		do_action( 'woocommerce_rest_insert_customer', $user_data, $request, false );
415
416
		$request->set_param( 'context', 'edit' );
417
		$response = $this->prepare_item_for_response( $user_data, $request );
418
		$response = rest_ensure_response( $response );
419
		return $response;
420
	}
421
422
	/**
423
	 * Delete a single customer.
424
	 *
425
	 * @param WP_REST_Request $request Full details about the request.
426
	 * @return WP_Error|WP_REST_Response
427
	 */
428
	public function delete_item( $request ) {
429
		$id       = (int) $request['id'];
430
		$reassign = isset( $request['reassign'] ) ? absint( $request['reassign'] ) : null;
431
		$force    = isset( $request['force'] ) ? (bool) $request['force'] : false;
432
433
		// We don't support trashing for this type, error out.
434
		if ( ! $force ) {
435
			return new WP_Error( 'woocommerce_rest_trash_not_supported', __( 'Customers do not support trashing.', 'woocommerce' ), array( 'status' => 501 ) );
436
		}
437
438
		$user_data = get_userdata( $id );
439
		if ( ! $user_data ) {
440
			return new WP_Error( 'woocommerce_rest_invalid_id', __( 'Invalid resource id.', 'woocommerce' ), array( 'status' => 400 ) );
441
		}
442
443
		if ( ! empty( $reassign ) ) {
444
			if ( $reassign === $id || ! get_userdata( $reassign ) ) {
445
				return new WP_Error( 'woocommerce_rest_customer_invalid_reassign', __( 'Invalid resource id for reassignment.', 'woocommerce' ), array( 'status' => 400 ) );
446
			}
447
		}
448
449
		$request->set_param( 'context', 'edit' );
450
		$response = $this->prepare_item_for_response( $user_data, $request );
451
452
		/** Include admin customer functions to get access to wp_delete_user() */
453
		require_once ABSPATH . 'wp-admin/includes/user.php';
454
455
		$customer = new WC_Customer( $id );
456
457
		if ( ! is_null( $reassign ) ) {
458
			$result = $customer->delete_and_reassign( $reassign );
459
		} else {
460
			$result = $customer->delete();
461
		}
462
463
		if ( ! $result ) {
464
			return new WP_Error( 'woocommerce_rest_cannot_delete', __( 'The resource cannot be deleted.', 'woocommerce' ), array( 'status' => 500 ) );
465
		}
466
467
		/**
468
		 * Fires after a customer is deleted via the REST API.
469
		 *
470
		 * @param WP_User          $user_data User data.
471
		 * @param WP_REST_Response $response  The response returned from the API.
472
		 * @param WP_REST_Request  $request   The request sent to the API.
473
		 */
474
		do_action( 'woocommerce_rest_delete_customer', $user_data, $response, $request );
475
476
		return $response;
477
	}
478
479
	/**
480
	 * Prepare a single customer output for response.
481
	 *
482
	 * @param WP_User           $user_data User object.
483
	 * @param WP_REST_Request   $request   Request object.
484
	 * @return WP_REST_Response $response  Response data.
485
	 */
486
	public function prepare_item_for_response( $user_data, $request ) {
487
		$customer = new WC_Customer( $user_data->ID );
488
		$data     = array(
489
			'id'               => $customer->get_id(),
490
			'date_created'     => wc_rest_prepare_date_response( date( 'Y-m-d H:i:s', $customer->get_date_created() ) ),
491
			'date_modified'    => $customer->get_date_modified() ? wc_rest_prepare_date_response( date( 'Y-m-d H:i:s', $customer->get_date_modified() ) ) : null,
492
			'email'            => $customer->get_email(),
493
			'first_name'       => $customer->get_first_name(),
494
			'last_name'        => $customer->get_last_name(),
495
			'username'         => $customer->get_username(),
496
			'last_order'       => array(
497
				'id'   => $customer->get_last_order_id(),
0 ignored issues
show
Bug introduced by
The method get_last_order_id() does not exist on WC_Customer. Did you maybe mean get_last_order()?

This check marks calls to methods that do not seem to exist on an object.

This is most likely the result of a method being renamed without all references to it being renamed likewise.

Loading history...
498
				'date' => wc_rest_prepare_date_response( $customer->get_last_order_date() ),
0 ignored issues
show
Bug introduced by
The method get_last_order_date() does not exist on WC_Customer. Did you maybe mean get_last_order()?

This check marks calls to methods that do not seem to exist on an object.

This is most likely the result of a method being renamed without all references to it being renamed likewise.

Loading history...
499
			),
500
			'orders_count'     => $customer->get_orders_count(),
0 ignored issues
show
Bug introduced by
The method get_orders_count() does not exist on WC_Customer. Did you maybe mean get_order_count()?

This check marks calls to methods that do not seem to exist on an object.

This is most likely the result of a method being renamed without all references to it being renamed likewise.

Loading history...
501
			'total_spent'      => $customer->get_total_spent(),
502
			'avatar_url'       => $customer->get_avatar_url(),
503
			'billing' => array(
504
				'first_name' => $customer->get_billing_first_name(),
505
				'last_name'  => $customer->get_billing_last_name(),
506
				'company'    => $customer->get_billing_company(),
507
				'address_1'  => $customer->get_billing_address_1(),
508
				'address_2'  => $customer->get_billing_address_2(),
509
				'city'       => $customer->get_billing_city(),
510
				'state'      => $customer->get_billing_state(),
511
				'postcode'   => $customer->get_billing_postcode(),
512
				'country'    => $customer->get_billing_country(),
513
				'email'      => $customer->get_billing_email(),
514
				'phone'      => $customer->get_billing_phone(),
515
			),
516
			'shipping' => array(
517
				'first_name' => $customer->get_shipping_first_name(),
518
				'last_name'  => $customer->get_shipping_last_name(),
519
				'company'    => $customer->get_shipping_company(),
520
				'address_1'  => $customer->get_shipping_address_1(),
521
				'address_2'  => $customer->get_shipping_address_2(),
522
				'city'       => $customer->get_shipping_city(),
523
				'state'      => $customer->get_shipping_state(),
524
				'postcode'   => $customer->get_shipping_postcode(),
525
				'country'    => $customer->get_shipping_country(),
526
			),
527
		);
528
529
		$context = ! empty( $request['context'] ) ? $request['context'] : 'view';
530
		$data    = $this->add_additional_fields_to_object( $data, $request );
531
		$data    = $this->filter_response_by_context( $data, $context );
532
533
		// Wrap the data in a response object.
534
		$response = rest_ensure_response( $data );
535
536
		$response->add_links( $this->prepare_links( $user_data ) );
537
538
		/**
539
		 * Filter customer data returned from the REST API.
540
		 *
541
		 * @param WP_REST_Response $response   The response object.
542
		 * @param WP_User          $user_data  User object used to create response.
543
		 * @param WP_REST_Request  $request    Request object.
544
		 */
545
		return apply_filters( 'woocommerce_rest_prepare_customer', $response, $user_data, $request );
546
	}
547
548
	/**
549
	 * Update customer meta fields.
550
	 *
551
	 * @param WC_Customer $customer
552
	 * @param WP_REST_Request $request
553
	 */
554
	protected function update_customer_meta_fields( $customer, $request ) {
555
		$schema = $this->get_item_schema();
556
557
		// Customer first name.
558
		if ( isset( $request['first_name'] ) ) {
559
			$customer->set_first_name( wc_clean( $request['first_name'] ) );
560
		}
561
562
		// Customer last name.
563
		if ( isset( $request['last_name'] ) ) {
564
			$customer->set_last_name( wc_clean( $request['last_name'] ) );
565
		}
566
567
		// Customer billing address.
568 View Code Duplication
		if ( isset( $request['billing'] ) ) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
569
			foreach ( array_keys( $schema['properties']['billing']['properties'] ) as $field ) {
570
				if ( isset( $request['billing'][ $field ] ) && is_callable( array( $customer, "set_billing_{$field}" ) ) ) {
571
					$customer->{"set_billing_{$field}"}( $request['billing'][ $field ]  );
572
				}
573
			}
574
		}
575
576
		// Customer shipping address.
577 View Code Duplication
		if ( isset( $request['shipping'] ) ) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
578
			foreach ( array_keys( $schema['properties']['shipping']['properties'] ) as $field ) {
579
				if ( isset( $request['shipping'][ $field ] ) && is_callable( array( $customer, "set_shipping_{$field}" ) ) ) {
580
					$customer->{"set_shipping_{$field}"}( $request['shipping'][ $field ]  );
581
				}
582
			}
583
		}
584
	}
585
586
	/**
587
	 * Prepare links for the request.
588
	 *
589
	 * @param WP_User $customer Customer object.
590
	 * @return array Links for the given customer.
591
	 */
592 View Code Duplication
	protected function prepare_links( $customer ) {
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
593
		$links = array(
594
			'self' => array(
595
				'href' => rest_url( sprintf( '/%s/%s/%d', $this->namespace, $this->rest_base, $customer->ID ) ),
596
			),
597
			'collection' => array(
598
				'href' => rest_url( sprintf( '/%s/%s', $this->namespace, $this->rest_base ) ),
599
			),
600
		);
601
602
		return $links;
603
	}
604
605
	/**
606
	 * Get the Customer's schema, conforming to JSON Schema.
607
	 *
608
	 * @return array
609
	 */
610
	public function get_item_schema() {
611
		$schema = array(
612
			'$schema'    => 'http://json-schema.org/draft-04/schema#',
613
			'title'      => 'customer',
614
			'type'       => 'object',
615
			'properties' => array(
616
				'id' => array(
617
					'description' => __( 'Unique identifier for the resource.', 'woocommerce' ),
618
					'type'        => 'integer',
619
					'context'     => array( 'view', 'edit' ),
620
					'readonly'    => true,
621
				),
622
				'date_created' => array(
623
					'description' => __( "The date the customer was created, in the site's timezone.", 'woocommerce' ),
624
					'type'        => 'date-time',
625
					'context'     => array( 'view', 'edit' ),
626
					'readonly'    => true,
627
				),
628
				'date_modified' => array(
629
					'description' => __( "The date the customer was last modified, in the site's timezone.", 'woocommerce' ),
630
					'type'        => 'date-time',
631
					'context'     => array( 'view', 'edit' ),
632
					'readonly'    => true,
633
				),
634
				'email' => array(
635
					'description' => __( 'The email address for the customer.', 'woocommerce' ),
636
					'type'        => 'string',
637
					'format'      => 'email',
638
					'context'     => array( 'view', 'edit' ),
639
				),
640
				'first_name' => array(
641
					'description' => __( 'Customer first name.', 'woocommerce' ),
642
					'type'        => 'string',
643
					'context'     => array( 'view', 'edit' ),
644
					'arg_options' => array(
645
						'sanitize_callback' => 'sanitize_text_field',
646
					),
647
				),
648
				'last_name' => array(
649
					'description' => __( 'Customer last name.', 'woocommerce' ),
650
					'type'        => 'string',
651
					'context'     => array( 'view', 'edit' ),
652
					'arg_options' => array(
653
						'sanitize_callback' => 'sanitize_text_field',
654
					),
655
				),
656
				'username' => array(
657
					'description' => __( 'Customer login name.', 'woocommerce' ),
658
					'type'        => 'string',
659
					'context'     => array( 'view', 'edit' ),
660
					'arg_options' => array(
661
						'sanitize_callback' => 'sanitize_user',
662
					),
663
				),
664
				'password' => array(
665
					'description' => __( 'Customer password.', 'woocommerce' ),
666
					'type'        => 'string',
667
					'context'     => array( 'edit' ),
668
				),
669
				'last_order' => array(
670
					'description' => __( 'Last order data.', 'woocommerce' ),
671
					'type'        => 'array',
672
					'context'     => array( 'view', 'edit' ),
673
					'readonly'    => true,
674
					'properties'  => array(
675
						'id' => array(
676
							'description' => __( 'Last order ID.', 'woocommerce' ),
677
							'type'        => 'integer',
678
							'context'     => array( 'view', 'edit' ),
679
							'readonly'    => true,
680
						),
681
						'date' => array(
682
							'description' => __( 'UTC DateTime of the customer last order.', 'woocommerce' ),
683
							'type'        => 'date-time',
684
							'context'     => array( 'view', 'edit' ),
685
							'readonly'    => true,
686
						),
687
					),
688
				),
689
				'orders_count' => array(
690
					'description' => __( 'Quantity of orders made by the customer.', 'woocommerce' ),
691
					'type'        => 'integer',
692
					'context'     => array( 'view', 'edit' ),
693
					'readonly'    => true,
694
				),
695
				'total_spent' => array(
696
					'description' => __( 'Total amount spent.', 'woocommerce' ),
697
					'type'        => 'string',
698
					'context'     => array( 'view', 'edit' ),
699
					'readonly'    => true,
700
				),
701
				'avatar_url' => array(
702
					'description' => __( 'Avatar URL.', 'woocommerce' ),
703
					'type'        => 'string',
704
					'context'     => array( 'view', 'edit' ),
705
					'readonly'    => true,
706
				),
707
				'billing' => array(
708
					'description' => __( 'List of billing address data.', 'woocommerce' ),
709
					'type'        => 'array',
710
					'context'     => array( 'view', 'edit' ),
711
					'properties' => array(
712
						'first_name' => array(
713
							'description' => __( 'First name.', 'woocommerce' ),
714
							'type'        => 'string',
715
							'context'     => array( 'view', 'edit' ),
716
						),
717
						'last_name' => array(
718
							'description' => __( 'Last name.', 'woocommerce' ),
719
							'type'        => 'string',
720
							'context'     => array( 'view', 'edit' ),
721
						),
722
						'company' => array(
723
							'description' => __( 'Company name.', 'woocommerce' ),
724
							'type'        => 'string',
725
							'context'     => array( 'view', 'edit' ),
726
						),
727
						'address_1' => array(
728
							'description' => __( 'Address line 1.', 'woocommerce' ),
729
							'type'        => 'string',
730
							'context'     => array( 'view', 'edit' ),
731
						),
732
						'address_2' => array(
733
							'description' => __( 'Address line 2.', 'woocommerce' ),
734
							'type'        => 'string',
735
							'context'     => array( 'view', 'edit' ),
736
						),
737
						'city' => array(
738
							'description' => __( 'City name.', 'woocommerce' ),
739
							'type'        => 'string',
740
							'context'     => array( 'view', 'edit' ),
741
						),
742
						'state' => array(
743
							'description' => __( 'ISO code or name of the state, province or district.', 'woocommerce' ),
744
							'type'        => 'string',
745
							'context'     => array( 'view', 'edit' ),
746
						),
747
						'postcode' => array(
748
							'description' => __( 'Postal code.', 'woocommerce' ),
749
							'type'        => 'string',
750
							'context'     => array( 'view', 'edit' ),
751
						),
752
						'country' => array(
753
							'description' => __( 'ISO code of the country.', 'woocommerce' ),
754
							'type'        => 'string',
755
							'context'     => array( 'view', 'edit' ),
756
						),
757
						'email' => array(
758
							'description' => __( 'Email address.', 'woocommerce' ),
759
							'type'        => 'string',
760
							'format'      => 'email',
761
							'context'     => array( 'view', 'edit' ),
762
						),
763
						'phone' => array(
764
							'description' => __( 'Phone number.', 'woocommerce' ),
765
							'type'        => 'string',
766
							'context'     => array( 'view', 'edit' ),
767
						),
768
					),
769
				),
770
				'shipping' => array(
771
					'description' => __( 'List of shipping address data.', 'woocommerce' ),
772
					'type'        => 'array',
773
					'context'     => array( 'view', 'edit' ),
774
					'properties' => array(
775
						'first_name' => array(
776
							'description' => __( 'First name.', 'woocommerce' ),
777
							'type'        => 'string',
778
							'context'     => array( 'view', 'edit' ),
779
						),
780
						'last_name' => array(
781
							'description' => __( 'Last name.', 'woocommerce' ),
782
							'type'        => 'string',
783
							'context'     => array( 'view', 'edit' ),
784
						),
785
						'company' => array(
786
							'description' => __( 'Company name.', 'woocommerce' ),
787
							'type'        => 'string',
788
							'context'     => array( 'view', 'edit' ),
789
						),
790
						'address_1' => array(
791
							'description' => __( 'Address line 1.', 'woocommerce' ),
792
							'type'        => 'string',
793
							'context'     => array( 'view', 'edit' ),
794
						),
795
						'address_2' => array(
796
							'description' => __( 'Address line 2.', 'woocommerce' ),
797
							'type'        => 'string',
798
							'context'     => array( 'view', 'edit' ),
799
						),
800
						'city' => array(
801
							'description' => __( 'City name.', 'woocommerce' ),
802
							'type'        => 'string',
803
							'context'     => array( 'view', 'edit' ),
804
						),
805
						'state' => array(
806
							'description' => __( 'ISO code or name of the state, province or district.', 'woocommerce' ),
807
							'type'        => 'string',
808
							'context'     => array( 'view', 'edit' ),
809
						),
810
						'postcode' => array(
811
							'description' => __( 'Postal code.', 'woocommerce' ),
812
							'type'        => 'string',
813
							'context'     => array( 'view', 'edit' ),
814
						),
815
						'country' => array(
816
							'description' => __( 'ISO code of the country.', 'woocommerce' ),
817
							'type'        => 'string',
818
							'context'     => array( 'view', 'edit' ),
819
						),
820
					),
821
				),
822
			),
823
		);
824
825
		return $this->add_additional_fields_schema( $schema );
826
	}
827
828
	/**
829
	 * Get role names.
830
	 *
831
	 * @return array
832
	 */
833
	protected function get_role_names() {
834
		global $wp_roles;
835
836
		return array_keys( $wp_roles->role_names );
837
	}
838
839
	/**
840
	 * Get the query params for collections.
841
	 *
842
	 * @return array
843
	 */
844
	public function get_collection_params() {
845
		$params = parent::get_collection_params();
846
847
		$params['context']['default'] = 'view';
848
849
		$params['exclude'] = array(
850
			'description'        => __( 'Ensure result set excludes specific IDs.', 'woocommerce' ),
851
			'type'               => 'array',
852
			'default'            => array(),
853
			'sanitize_callback'  => 'wp_parse_id_list',
854
		);
855
		$params['include'] = array(
856
			'description'        => __( 'Limit result set to specific IDs.', 'woocommerce' ),
857
			'type'               => 'array',
858
			'default'            => array(),
859
			'sanitize_callback'  => 'wp_parse_id_list',
860
		);
861
		$params['offset'] = array(
862
			'description'        => __( 'Offset the result set by a specific number of items.', 'woocommerce' ),
863
			'type'               => 'integer',
864
			'sanitize_callback'  => 'absint',
865
			'validate_callback'  => 'rest_validate_request_arg',
866
		);
867
		$params['order'] = array(
868
			'default'            => 'asc',
869
			'description'        => __( 'Order sort attribute ascending or descending.', 'woocommerce' ),
870
			'enum'               => array( 'asc', 'desc' ),
871
			'sanitize_callback'  => 'sanitize_key',
872
			'type'               => 'string',
873
			'validate_callback'  => 'rest_validate_request_arg',
874
		);
875
		$params['orderby'] = array(
876
			'default'            => 'name',
877
			'description'        => __( 'Sort collection by object attribute.', 'woocommerce' ),
878
			'enum'               => array(
879
				'id',
880
				'include',
881
				'name',
882
				'registered_date',
883
			),
884
			'sanitize_callback'  => 'sanitize_key',
885
			'type'               => 'string',
886
			'validate_callback'  => 'rest_validate_request_arg',
887
		);
888
		$params['email'] = array(
889
			'description'        => __( 'Limit result set to resources with a specific email.', 'woocommerce' ),
890
			'type'               => 'string',
891
			'format'             => 'email',
892
			'validate_callback'  => 'rest_validate_request_arg',
893
		);
894
		$params['role'] = array(
895
			'description'        => __( 'Limit result set to resources with a specific role.', 'woocommerce' ),
896
			'type'               => 'string',
897
			'default'            => 'customer',
898
			'enum'               => array_merge( array( 'all' ), $this->get_role_names() ),
899
			'validate_callback'  => 'rest_validate_request_arg',
900
		);
901
		return $params;
902
	}
903
}
904