Completed
Push — master ( 8d2357...6fafe2 )
by Claudio
07:22
created

WC_REST_Posts_Controller   C

Complexity

Total Complexity 68

Size/Duplication

Total Lines 678
Duplicated Lines 15.93 %

Coupling/Cohesion

Components 1
Dependencies 1

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 108
loc 678
rs 5.1661
wmc 68
lcom 1
cbo 1

19 Methods

Rating   Name   Duplication   Size   Complexity  
A get_items_permissions_check() 7 7 2
A create_item_permissions_check() 7 7 2
A get_item_permissions_check() 9 9 3
A update_item_permissions_check() 9 9 3
A delete_item_permissions_check() 9 9 3
A update_post_meta_fields() 0 3 1
A batch_items_permissions_check() 7 7 2
A get_post_types() 0 3 1
B get_item() 0 17 5
A add_post_meta_fields() 0 3 1
A delete_post() 0 3 1
F get_items() 13 99 11
A prepare_links() 12 12 1
B prepare_items_query() 0 26 4
A get_allowed_query_vars() 0 63 2
B get_collection_params() 0 78 3
B create_item() 9 53 6
C update_item() 8 45 8
C delete_item() 18 62 9

How to fix   Duplicated Code    Complexity   

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:

Complex Class

 Tip:   Before tackling complexity, make sure that you eliminate any duplication first. This often can reduce the size of classes significantly.

Complex classes like WC_REST_Posts_Controller often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes. You can also have a look at the cohesion graph to spot any un-connected, or weakly-connected components.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

While breaking up the class, it is a good idea to analyze how other classes use WC_REST_Posts_Controller, and based on these observations, apply Extract Interface, too.

1
<?php
2
3
if ( ! defined( 'ABSPATH' ) ) {
4
	exit;
5
}
6
7
/**
8
 * Abstract Rest Posts Controler Class
9
 *
10
 * @author   WooThemes
11
 * @category API
12
 * @package  WooCommerce/Abstracts
13
 * @version  2.6.0
14
 */
15
abstract class WC_REST_Posts_Controller extends WC_REST_Controller {
16
17
	/**
18
	 * Endpoint namespace.
19
	 *
20
	 * @var string
21
	 */
22
	protected $namespace = 'wc/v1';
23
24
	/**
25
	 * Route base.
26
	 *
27
	 * @var string
28
	 */
29
	protected $rest_base = '';
30
31
	/**
32
	 * Post type.
33
	 *
34
	 * @var string
35
	 */
36
	protected $post_type = '';
37
38
	/**
39
	 * Controls visibility on frontend.
40
	 *
41
	 * @var string
42
	 */
43
	protected $public = false;
44
45
	/**
46
	 * Check if a given request has access to read items.
47
	 *
48
	 * @param  WP_REST_Request $request Full details about the request.
49
	 * @return WP_Error|boolean
50
	 */
51 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...
52
		if ( ! wc_rest_check_post_permissions( $this->post_type, 'read' ) ) {
53
			return new WP_Error( 'woocommerce_rest_cannot_view', __( 'Sorry, you cannot list resources.', 'woocommerce' ), array( 'status' => rest_authorization_required_code() ) );
54
		}
55
56
		return true;
57
	}
58
59
	/**
60
	 * Check if a given request has access to create an item.
61
	 *
62
	 * @param  WP_REST_Request $request Full details about the request.
63
	 * @return WP_Error|boolean
64
	 */
65 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...
66
		if ( ! wc_rest_check_post_permissions( $this->post_type, 'create' ) ) {
67
			return new WP_Error( 'woocommerce_rest_cannot_create', __( 'Sorry, you are not allowed to create resources.', 'woocommerce' ), array( 'status' => rest_authorization_required_code() ) );
68
		}
69
70
		return true;
71
	}
72
73
	/**
74
	 * Check if a given request has access to read an item.
75
	 *
76
	 * @param  WP_REST_Request $request Full details about the request.
77
	 * @return WP_Error|boolean
78
	 */
79 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...
80
		$post = get_post( (int) $request['id'] );
81
82
		if ( $post && ! wc_rest_check_post_permissions( $this->post_type, 'read', $post->ID ) ) {
83
			return new WP_Error( 'woocommerce_rest_cannot_view', __( 'Sorry, you cannot view this resource.', 'woocommerce' ), array( 'status' => rest_authorization_required_code() ) );
84
		}
85
86
		return true;
87
	}
88
89
	/**
90
	 * Check if a given request has access to update an item.
91
	 *
92
	 * @param  WP_REST_Request $request Full details about the request.
93
	 * @return WP_Error|boolean
94
	 */
95 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...
96
		$post = get_post( $request['id'] );
97
98
		if ( $post && ! wc_rest_check_post_permissions( $this->post_type, 'edit', $post->ID ) ) {
99
			return new WP_Error( 'woocommerce_rest_cannot_edit', __( 'Sorry, you are not allowed to edit this resource.', 'woocommerce' ), array( 'status' => rest_authorization_required_code() ) );
100
		}
101
102
		return true;
103
	}
104
105
	/**
106
	 * Check if a given request has access to delete an item.
107
	 *
108
	 * @param  WP_REST_Request $request Full details about the request.
109
	 * @return bool|WP_Error
110
	 */
111 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...
112
		$post = get_post( $request['id'] );
113
114
		if ( $post && ! wc_rest_check_post_permissions( $this->post_type, 'delete', $post->ID ) ) {
115
			return new WP_Error( 'woocommerce_rest_cannot_delete', __( 'Sorry, you are not allowed to delete this resource.', 'woocommerce' ), array( 'status' => rest_authorization_required_code() ) );
116
		}
117
118
		return true;
119
	}
120
121
	/**
122
	 * Check if a given request has access batch create, update and delete items.
123
	 *
124
	 * @param  WP_REST_Request $request Full details about the request.
125
	 * @return boolean
126
	 */
127 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...
128
		if ( ! wc_rest_check_post_permissions( $this->post_type, 'batch' ) ) {
129
			return new WP_Error( 'woocommerce_rest_cannot_batch', __( 'Sorry, you are not allowed to manipule this resource.', 'woocommerce' ), array( 'status' => rest_authorization_required_code() ) );
130
		}
131
132
		return true;
133
	}
134
135
	/**
136
	 * Get post types.
137
	 *
138
	 * @return array
139
	 */
140
	protected function get_post_types() {
141
		return array( $this->post_type );
142
	}
143
144
	/**
145
	 * Get a single item.
146
	 *
147
	 * @param WP_REST_Request $request Full details about the request.
148
	 * @return WP_Error|WP_REST_Response
149
	 */
150
	public function get_item( $request ) {
151
		$id   = (int) $request['id'];
152
		$post = get_post( $id );
153
154
		if ( empty( $id ) || empty( $post->ID ) || ! in_array( $post->post_type, $this->get_post_types() ) ) {
155
			return new WP_Error( "woocommerce_rest_invalid_{$this->post_type}_id", __( 'Invalid id.', 'woocommerce' ), array( 'status' => 404 ) );
156
		}
157
158
		$data = $this->prepare_item_for_response( $post, $request );
159
		$response = rest_ensure_response( $data );
160
161
		if ( $this->public ) {
162
			$response->link_header( 'alternate', get_permalink( $id ), array( 'type' => 'text/html' ) );
163
		}
164
165
		return $response;
166
	}
167
168
	/**
169
	 * Create a single item.
170
	 *
171
	 * @param WP_REST_Request $request Full details about the request.
172
	 * @return WP_Error|WP_REST_Response
173
	 */
174
	public function create_item( $request ) {
175
		if ( ! empty( $request['id'] ) ) {
176
			return new WP_Error( "woocommerce_rest_{$this->post_type}_exists", sprintf( __( 'Cannot create existing %s.', 'woocommerce' ), $this->post_type ), array( 'status' => 400 ) );
177
		}
178
179
		$post = $this->prepare_item_for_database( $request );
180
		if ( is_wp_error( $post ) ) {
181
			return $post;
182
		}
183
184
		$post->post_type = $this->post_type;
185
		$post_id         = wp_insert_post( $post, true );
186
187 View Code Duplication
		if ( is_wp_error( $post_id ) ) {
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...
188
189
			if ( in_array( $post_id->get_error_code(), array( 'db_insert_error' ) ) ) {
190
				$post_id->add_data( array( 'status' => 500 ) );
191
			} else {
192
				$post_id->add_data( array( 'status' => 400 ) );
193
			}
194
			return $post_id;
195
		}
196
		$post->ID = $post_id;
197
		$post     = get_post( $post_id );
198
199
		$this->update_additional_fields_for_object( $post, $request );
200
201
		// Add meta fields.
202
		$meta_fields = $this->add_post_meta_fields( $post, $request );
203
		if ( is_wp_error( $meta_fields ) ) {
204
			// Remove post.
205
			$this->delete_post( $post );
206
207
			return $meta_fields;
208
		}
209
210
		/**
211
		 * Fires after a single item is created or updated via the REST API.
212
		 *
213
		 * @param object          $post      Inserted object (not a WP_Post object).
214
		 * @param WP_REST_Request $request   Request object.
215
		 * @param boolean         $creating  True when creating item, false when updating.
216
		 */
217
		do_action( "woocommerce_rest_insert_{$this->post_type}", $post, $request, true );
218
219
		$request->set_param( 'context', 'edit' );
220
		$response = $this->prepare_item_for_response( $post, $request );
221
		$response = rest_ensure_response( $response );
222
		$response->set_status( 201 );
223
		$response->header( 'Location', rest_url( sprintf( '/%s/%s/%d', $this->namespace, $this->rest_base, $post_id ) ) );
224
225
		return $response;
226
	}
227
228
	/**
229
	 * Add post meta fields.
230
	 *
231
	 * @param WP_Post $post
232
	 * @param WP_REST_Request $request
233
	 * @return bool|WP_Error
234
	 */
235
	protected function add_post_meta_fields( $post, $request ) {
236
		return true;
237
	}
238
239
	/**
240
	 * Delete post.
241
	 *
242
	 * @param WP_Post $post
243
	 */
244
	protected function delete_post( $post ) {
245
		wp_delete_post( $post->ID, true );
246
	}
247
248
	/**
249
	 * Update a single post.
250
	 *
251
	 * @param WP_REST_Request $request Full details about the request.
252
	 * @return WP_Error|WP_REST_Response
253
	 */
254
	public function update_item( $request ) {
255
		$id   = (int) $request['id'];
256
		$post = get_post( $id );
257
258
		if ( empty( $id ) || empty( $post->ID ) || ! in_array( $post->post_type, $this->get_post_types() ) ) {
259
			return new WP_Error( "woocommerce_rest_{$this->post_type}_invalid_id", __( 'ID is invalid.', 'woocommerce' ), array( 'status' => 400 ) );
260
		}
261
262
		$post = $this->prepare_item_for_database( $request );
263
		if ( is_wp_error( $post ) ) {
264
			return $post;
265
		}
266
		// Convert the post object to an array, otherwise wp_update_post will expect non-escaped input.
267
		$post_id = wp_update_post( (array) $post, true );
268 View Code Duplication
		if ( is_wp_error( $post_id ) ) {
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...
269
			if ( in_array( $post_id->get_error_code(), array( 'db_update_error' ) ) ) {
270
				$post_id->add_data( array( 'status' => 500 ) );
271
			} else {
272
				$post_id->add_data( array( 'status' => 400 ) );
273
			}
274
			return $post_id;
275
		}
276
277
		$post = get_post( $post_id );
278
		$this->update_additional_fields_for_object( $post, $request );
279
280
		// Update meta fields.
281
		$meta_fields = $this->update_post_meta_fields( $post, $request );
282
		if ( is_wp_error( $meta_fields ) ) {
283
			return $meta_fields;
284
		}
285
286
		/**
287
		 * Fires after a single item is created or updated via the REST API.
288
		 *
289
		 * @param object          $post      Inserted object (not a WP_Post object).
290
		 * @param WP_REST_Request $request   Request object.
291
		 * @param boolean         $creating  True when creating item, false when updating.
292
		 */
293
		do_action( "woocommerce_rest_insert_{$this->post_type}", $post, $request, false );
294
295
		$request->set_param( 'context', 'edit' );
296
		$response = $this->prepare_item_for_response( $post, $request );
297
		return rest_ensure_response( $response );
298
	}
299
300
	/**
301
	 * Get a collection of posts.
302
	 *
303
	 * @param WP_REST_Request $request Full details about the request.
304
	 * @return WP_Error|WP_REST_Response
305
	 */
306
	public function get_items( $request ) {
307
		$args                         = array();
308
		$args['offset']               = $request['offset'];
309
		$args['order']                = $request['order'];
310
		$args['orderby']              = $request['orderby'];
311
		$args['paged']                = $request['page'];
312
		$args['post__in']             = $request['include'];
313
		$args['post__not_in']         = $request['exclude'];
314
		$args['posts_per_page']       = $request['per_page'];
315
		$args['name']                 = $request['slug'];
316
		$args['post_parent__in']      = $request['parent'];
317
		$args['post_parent__not_in']  = $request['parent_exclude'];
318
		$args['s']                    = $request['search'];
319
320
		$args['date_query'] = array();
321
		// Set before into date query. Date query must be specified as an array of an array.
322
		if ( isset( $request['before'] ) ) {
323
			$args['date_query'][0]['before'] = $request['before'];
324
		}
325
326
		// Set after into date query. Date query must be specified as an array of an array.
327
		if ( isset( $request['after'] ) ) {
328
			$args['date_query'][0]['after'] = $request['after'];
329
		}
330
331
		if ( is_array( $request['filter'] ) ) {
332
			$args = array_merge( $args, $request['filter'] );
333
			unset( $args['filter'] );
334
		}
335
336
		// Force the post_type argument, since it's not a user input variable.
337
		$args['post_type'] = $this->post_type;
338
339
		/**
340
		 * Filter the query arguments for a request.
341
		 *
342
		 * Enables adding extra arguments or setting defaults for a post
343
		 * collection request.
344
		 *
345
		 * @param array           $args    Key value array of query var to query value.
346
		 * @param WP_REST_Request $request The request used.
347
		 */
348
		$args = apply_filters( "woocommerce_rest_{$this->post_type}_query", $args, $request );
349
		$query_args = $this->prepare_items_query( $args, $request );
350
351
		$posts_query = new WP_Query();
352
		$query_result = $posts_query->query( $query_args );
353
354
		$posts = array();
355
		foreach ( $query_result as $post ) {
356
			if ( ! wc_rest_check_post_permissions( $this->post_type, 'read', $post->ID ) ) {
357
				continue;
358
			}
359
360
			$data = $this->prepare_item_for_response( $post, $request );
361
			$posts[] = $this->prepare_response_for_collection( $data );
362
		}
363
364
		$page = (int) $query_args['paged'];
365
		$total_posts = $posts_query->found_posts;
366
367
		if ( $total_posts < 1 ) {
368
			// Out-of-bounds, run the query again without LIMIT for total count
369
			unset( $query_args['paged'] );
370
			$count_query = new WP_Query();
371
			$count_query->query( $query_args );
372
			$total_posts = $count_query->found_posts;
373
		}
374
375
		$max_pages = ceil( $total_posts / (int) $query_args['posts_per_page'] );
376
377
		$response = rest_ensure_response( $posts );
378
		$response->header( 'X-WP-Total', (int) $total_posts );
379
		$response->header( 'X-WP-TotalPages', (int) $max_pages );
380
381
		$request_params = $request->get_query_params();
382
		if ( ! empty( $request_params['filter'] ) ) {
383
			// Normalize the pagination params.
384
			unset( $request_params['filter']['posts_per_page'] );
385
			unset( $request_params['filter']['paged'] );
386
		}
387
		$base = add_query_arg( $request_params, rest_url( sprintf( '/%s/%s', $this->namespace, $this->rest_base ) ) );
388
389 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...
390
			$prev_page = $page - 1;
391
			if ( $prev_page > $max_pages ) {
392
				$prev_page = $max_pages;
393
			}
394
			$prev_link = add_query_arg( 'page', $prev_page, $base );
395
			$response->link_header( 'prev', $prev_link );
396
		}
397 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...
398
			$next_page = $page + 1;
399
			$next_link = add_query_arg( 'page', $next_page, $base );
400
			$response->link_header( 'next', $next_link );
401
		}
402
403
		return $response;
404
	}
405
406
	/**
407
	 * Delete a single item.
408
	 *
409
	 * @param WP_REST_Request $request Full details about the request.
410
	 * @return WP_REST_Response|WP_Error
411
	 */
412
	public function delete_item( $request ) {
413
		$id    = (int) $request['id'];
414
		$force = (bool) $request['force'];
415
		$post  = get_post( $id );
416
417
		if ( empty( $id ) || empty( $post->ID ) || ! in_array( $post->post_type, $this->get_post_types() ) ) {
418
			return new WP_Error( "woocommerce_rest_{$this->post_type}_invalid_id", __( 'Invalid post id.', 'woocommerce' ), array( 'status' => 404 ) );
419
		}
420
421
		$supports_trash = EMPTY_TRASH_DAYS > 0;
422
423
		/**
424
		 * Filter whether an item is trashable.
425
		 *
426
		 * Return false to disable trash support for the item.
427
		 *
428
		 * @param boolean $supports_trash Whether the item type support trashing.
429
		 * @param WP_Post $post           The Post object being considered for trashing support.
430
		 */
431
		$supports_trash = apply_filters( "woocommerce_rest_{$this->post_type}_trashable", $supports_trash, $post );
432
433 View Code Duplication
		if ( ! wc_rest_check_post_permissions( $this->post_type, 'delete', $post->ID ) ) {
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...
434
			return new WP_Error( "woocommerce_rest_user_cannot_delete_{$this->post_type}", sprintf( __( 'Sorry, you are not allowed to delete %s.', 'woocommerce' ), $this->post_type ), array( 'status' => rest_authorization_required_code() ) );
435
		}
436
437
		$request->set_param( 'context', 'edit' );
438
		$response = $this->prepare_item_for_response( $post, $request );
439
440
		// If we're forcing, then delete permanently.
441
		if ( $force ) {
442
			$result = wp_delete_post( $id, true );
443 View Code Duplication
		} else {
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...
444
			// If we don't support trashing for this type, error out.
445
			if ( ! $supports_trash ) {
446
				return new WP_Error( 'woocommerce_rest_trash_not_supported', sprintf( __( 'The %s does not support trashing.', 'woocommerce' ), $this->post_type ), array( 'status' => 501 ) );
447
			}
448
449
			// Otherwise, only trash if we haven't already.
450
			if ( 'trash' === $post->post_status ) {
451
				return new WP_Error( 'woocommerce_rest_already_trashed', sprintf( __( 'The %s has already been deleted.', 'woocommerce' ), $this->post_type ), array( 'status' => 410 ) );
452
			}
453
454
			// (Note that internally this falls through to `wp_delete_post` if
455
			// the trash is disabled.)
456
			$result = wp_trash_post( $id );
457
		}
458
459
		if ( ! $result ) {
460
			return new WP_Error( 'woocommerce_rest_cannot_delete', sprintf( __( 'The %s cannot be deleted.', 'woocommerce' ), $this->post_type ), array( 'status' => 500 ) );
461
		}
462
463
		/**
464
		 * Fires after a single item is deleted or trashed via the REST API.
465
		 *
466
		 * @param object           $post     The deleted or trashed item.
467
		 * @param WP_REST_Response $response The response data.
468
		 * @param WP_REST_Request  $request  The request sent to the API.
469
		 */
470
		do_action( "woocommerce_rest_delete_{$this->post_type}", $post, $response, $request );
471
472
		return $response;
473
	}
474
475
	/**
476
	 * Prepare links for the request.
477
	 *
478
	 * @param WP_Post $post Post object.
479
	 * @return array Links for the given post.
480
	 */
481 View Code Duplication
	protected function prepare_links( $post ) {
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...
482
		$links = array(
483
			'self' => array(
484
				'href' => rest_url( sprintf( '/%s/%s/%d', $this->namespace, $this->rest_base, $post->ID ) ),
485
			),
486
			'collection' => array(
487
				'href' => rest_url( sprintf( '/%s/%s', $this->namespace, $this->rest_base ) ),
488
			),
489
		);
490
491
		return $links;
492
	}
493
494
	/**
495
	 * Determine the allowed query_vars for a get_items() response and
496
	 * prepare for WP_Query.
497
	 *
498
	 * @param array           $prepared_args
499
	 * @param WP_REST_Request $request
500
	 * @return array          $query_args
501
	 */
502
	protected function prepare_items_query( $prepared_args = array(), $request = null ) {
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...
503
504
		$valid_vars = array_flip( $this->get_allowed_query_vars() );
505
		$query_args = array();
506
		foreach ( $valid_vars as $var => $index ) {
507
			if ( isset( $prepared_args[ $var ] ) ) {
508
				/**
509
				 * Filter the query_vars used in `get_items` for the constructed query.
510
				 *
511
				 * The dynamic portion of the hook name, $var, refers to the query_var key.
512
				 *
513
				 * @param mixed $prepared_args[ $var ] The query_var value.
514
				 *
515
				 */
516
				$query_args[ $var ] = apply_filters( "woocommerce_rest_query_var-{$var}", $prepared_args[ $var ] );
517
			}
518
		}
519
520
		$query_args['ignore_sticky_posts'] = true;
521
522
		if ( 'include' === $query_args['orderby'] ) {
523
			$query_args['orderby'] = 'post__in';
524
		}
525
526
		return $query_args;
527
	}
528
529
	/**
530
	 * Get all the WP Query vars that are allowed for the API request.
531
	 *
532
	 * @return array
533
	 */
534
	protected function get_allowed_query_vars() {
535
		global $wp;
536
537
		/**
538
		 * Filter the publicly allowed query vars.
539
		 *
540
		 * Allows adjusting of the default query vars that are made public.
541
		 *
542
		 * @param array  Array of allowed WP_Query query vars.
543
		 */
544
		$valid_vars = apply_filters( 'query_vars', $wp->public_query_vars );
545
546
		$post_type_obj = get_post_type_object( $this->post_type );
547
		if ( current_user_can( $post_type_obj->cap->edit_posts ) ) {
548
			/**
549
			 * Filter the allowed 'private' query vars for authorized users.
550
			 *
551
			 * If the user has the `edit_posts` capability, we also allow use of
552
			 * private query parameters, which are only undesirable on the
553
			 * frontend, but are safe for use in query strings.
554
			 *
555
			 * To disable anyway, use
556
			 * `add_filter( 'woocommerce_rest_private_query_vars', '__return_empty_array' );`
557
			 *
558
			 * @param array $private_query_vars Array of allowed query vars for authorized users.
559
			 * }
560
			 */
561
			$private = apply_filters( 'woocommerce_rest_private_query_vars', $wp->private_query_vars );
562
			$valid_vars = array_merge( $valid_vars, $private );
563
		}
564
		// Define our own in addition to WP's normal vars.
565
		$rest_valid = array(
566
			'date_query',
567
			'ignore_sticky_posts',
568
			'offset',
569
			'post__in',
570
			'post__not_in',
571
			'post_parent',
572
			'post_parent__in',
573
			'post_parent__not_in',
574
			'posts_per_page',
575
			'meta_query',
576
			'tax_query',
577
		);
578
		$valid_vars = array_merge( $valid_vars, $rest_valid );
579
580
		/**
581
		 * Filter allowed query vars for the REST API.
582
		 *
583
		 * This filter allows you to add or remove query vars from the final allowed
584
		 * list for all requests, including unauthenticated ones. To alter the
585
		 * vars for editors only.
586
		 *
587
		 * @param array {
588
		 *    Array of allowed WP_Query query vars.
589
		 *
590
		 *    @param string $allowed_query_var The query var to allow.
591
		 * }
592
		 */
593
		$valid_vars = apply_filters( 'woocommerce_rest_query_vars', $valid_vars );
594
595
		return $valid_vars;
596
	}
597
598
	/**
599
	 * Get the query params for collections of attachments.
600
	 *
601
	 * @return array
602
	 */
603
	public function get_collection_params() {
604
		$params = parent::get_collection_params();
605
606
		$params['context']['default'] = 'view';
607
608
		$params['after'] = array(
609
			'description'        => __( 'Limit response to resources published after a given ISO8601 compliant date.', 'woocommerce' ),
610
			'type'               => 'string',
611
			'format'             => 'date-time',
612
			'validate_callback'  => 'rest_validate_request_arg',
613
		);
614
		$params['before'] = array(
615
			'description'        => __( 'Limit response to resources published before a given ISO8601 compliant date.', 'woocommerce' ),
616
			'type'               => 'string',
617
			'format'             => 'date-time',
618
			'validate_callback'  => 'rest_validate_request_arg',
619
		);
620
		$params['exclude'] = array(
621
			'description'        => __( 'Ensure result set excludes specific ids.', 'woocommerce' ),
622
			'type'               => 'array',
623
			'default'            => array(),
624
			'sanitize_callback'  => 'wp_parse_id_list',
625
		);
626
		$params['include'] = array(
627
			'description'        => __( 'Limit result set to specific ids.', 'woocommerce' ),
628
			'type'               => 'array',
629
			'default'            => array(),
630
			'sanitize_callback'  => 'wp_parse_id_list',
631
		);
632
		$params['offset'] = array(
633
			'description'        => __( 'Offset the result set by a specific number of items.', 'woocommerce' ),
634
			'type'               => 'integer',
635
			'sanitize_callback'  => 'absint',
636
			'validate_callback'  => 'rest_validate_request_arg',
637
		);
638
		$params['order'] = array(
639
			'description'        => __( 'Order sort attribute ascending or descending.', 'woocommerce' ),
640
			'type'               => 'string',
641
			'default'            => 'desc',
642
			'enum'               => array( 'asc', 'desc' ),
643
			'validate_callback'  => 'rest_validate_request_arg',
644
		);
645
		$params['orderby'] = array(
646
			'description'        => __( 'Sort collection by object attribute.', 'woocommerce' ),
647
			'type'               => 'string',
648
			'default'            => 'date',
649
			'enum'               => array(
650
				'date',
651
				'id',
652
				'include',
653
				'title',
654
				'slug',
655
			),
656
			'validate_callback'  => 'rest_validate_request_arg',
657
		);
658
659
		$post_type_obj = get_post_type_object( $this->post_type );
660
		if ( isset( $post_type_obj->hierarchical ) && $post_type_obj->hierarchical ) {
661
			$params['parent'] = array(
662
				'description'       => __( 'Limit result set to those of particular parent ids.', 'woocommerce' ),
663
				'type'              => 'array',
664
				'sanitize_callback' => 'wp_parse_id_list',
665
				'default'           => array(),
666
			);
667
			$params['parent_exclude'] = array(
668
				'description'       => __( 'Limit result set to all items except those of a particular parent id.', 'woocommerce' ),
669
				'type'              => 'array',
670
				'sanitize_callback' => 'wp_parse_id_list',
671
				'default'           => array(),
672
			);
673
		}
674
675
		$params['filter'] = array(
676
			'description' => __( 'Use WP Query arguments to modify the response; private query vars require appropriate authorization.', 'woocommerce' ),
677
		);
678
679
		return $params;
680
	}
681
682
	/**
683
	 * Update post meta fields.
684
	 *
685
	 * @param WP_Post $post
686
	 * @param WP_REST_Request $request
687
	 * @return bool|WP_Error
688
	 */
689
	protected function update_post_meta_fields( $post, $request ) {
690
		return true;
691
	}
692
}
693