Completed
Push — master ( 9a7f47...7f2ea5 )
by Mike
05:50
created

AbstractObjectsController::add_meta_query()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 8
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 2
eloc 4
nc 2
nop 2
dl 0
loc 8
rs 10
c 0
b 0
f 0
1
<?php
2
/**
3
 * Abstract Rest CRUD Controller Class
4
 *
5
 * @package WooCommerce/RestApi
6
 */
7
8
namespace WooCommerce\RestApi\Controllers\Version4;
9
10
defined( 'ABSPATH' ) || exit;
11
12
/**
13
 * CRUD Object Controller.
14
 */
15
abstract class AbstractObjectsController extends AbstractController {
16
17
	/**
18
	 * If object is hierarchical.
19
	 *
20
	 * @var bool
21
	 */
22
	protected $hierarchical = false;
23
24
	/**
25
	 * Post type.
26
	 *
27
	 * @var string
28
	 */
29
	protected $post_type = '';
30
31
	/**
32
	 * Get object.
33
	 *
34
	 * @param  int $id Object ID.
35
	 * @return \WC_Data|bool
36
	 */
37
	abstract protected function get_object( $id );
38
39
	/**
40
	 * Prepares the object for the REST response.
41
	 *
42
	 * @since  3.0.0
43
	 * @param  \WC_Data         $object  Object data.
44
	 * @param  \WP_REST_Request $request Request object.
45
	 * @return \WP_REST_Response Response object on success, or \WP_Error object on failure.
46
	 */
47
	abstract protected function prepare_object_for_response( $object, $request );
48
49
	/**
50
	 * Prepares one object for create or update operation.
51
	 *
52
	 * @since  3.0.0
53
	 * @param  \WP_REST_Request $request Request object.
54
	 * @param  bool             $creating If is creating a new object.
55
	 * @return \WC_Data The prepared item, or \WP_Error object on failure.
56
	 */
57
	abstract protected function prepare_object_for_database( $request, $creating = false );
58
59
	/**
60
	 * Register the routes for products.
61
	 */
62
	public function register_routes() {
63
		$this->register_items_route();
64
		$this->register_item_route();
65
		$this->register_batch_route();
66
	}
67
68
	/**
69
	 * Check if a given request has access to read items.
70
	 *
71
	 * @param  \WP_REST_Request $request Full details about the request.
72
	 * @return \WP_Error|boolean
73
	 */
74
	public function get_items_permissions_check( $request ) {
75
		if ( ! wc_rest_check_post_permissions( $this->post_type, 'read' ) ) {
76
			return new \WP_Error( 'woocommerce_rest_cannot_view', __( 'Sorry, you cannot list resources.', 'woocommerce' ), array( 'status' => rest_authorization_required_code() ) );
77
		}
78
79
		return true;
80
	}
81
82
	/**
83
	 * Check if a given request has access to read an item.
84
	 *
85
	 * @param  \WP_REST_Request $request Full details about the request.
86
	 * @return \WP_Error|boolean
87
	 */
88
	public function get_item_permissions_check( $request ) {
89
		$object = $this->get_object( (int) $request['id'] );
90
91
		if ( $object && 0 !== $object->get_id() && ! wc_rest_check_post_permissions( $this->post_type, 'read', $object->get_id() ) ) {
92
			return new \WP_Error( 'woocommerce_rest_cannot_view', __( 'Sorry, you cannot view this resource.', 'woocommerce' ), array( 'status' => rest_authorization_required_code() ) );
93
		}
94
95
		return true;
96
	}
97
98
	/**
99
	 * Check if a given request has access to create an item.
100
	 *
101
	 * @param  \WP_REST_Request $request Full details about the request.
102
	 * @return \WP_Error|boolean
103
	 */
104
	public function create_item_permissions_check( $request ) {
105
		if ( ! wc_rest_check_post_permissions( $this->post_type, 'create' ) ) {
106
			return new \WP_Error( 'woocommerce_rest_cannot_create', __( 'Sorry, you are not allowed to create resources.', 'woocommerce' ), array( 'status' => rest_authorization_required_code() ) );
107
		}
108
109
		return true;
110
	}
111
112
	/**
113
	 * Check if a given request has access to update an item.
114
	 *
115
	 * @param  \WP_REST_Request $request Full details about the request.
116
	 * @return \WP_Error|boolean
117
	 */
118
	public function update_item_permissions_check( $request ) {
119
		$object = $this->get_object( (int) $request['id'] );
120
121
		if ( $object && 0 !== $object->get_id() && ! wc_rest_check_post_permissions( $this->post_type, 'edit', $object->get_id() ) ) {
122
			return new \WP_Error( 'woocommerce_rest_cannot_edit', __( 'Sorry, you are not allowed to edit this resource.', 'woocommerce' ), array( 'status' => rest_authorization_required_code() ) );
123
		}
124
125
		return true;
126
	}
127
128
	/**
129
	 * Check if a given request has access to delete an item.
130
	 *
131
	 * @param  \WP_REST_Request $request Full details about the request.
132
	 * @return bool|\WP_Error
133
	 */
134
	public function delete_item_permissions_check( $request ) {
135
		$object = $this->get_object( (int) $request['id'] );
136
137
		if ( $object && 0 !== $object->get_id() && ! wc_rest_check_post_permissions( $this->post_type, 'delete', $object->get_id() ) ) {
138
			return new \WP_Error( 'woocommerce_rest_cannot_delete', __( 'Sorry, you are not allowed to delete this resource.', 'woocommerce' ), array( 'status' => rest_authorization_required_code() ) );
139
		}
140
141
		return true;
142
	}
143
144
	/**
145
	 * Check if a given request has access batch create, update and delete items.
146
	 *
147
	 * @param  \WP_REST_Request $request Full details about the request.
148
	 *
149
	 * @return boolean|\WP_Error
150
	 */
151
	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. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-unused  annotation

151
	public function batch_items_permissions_check( /** @scrutinizer ignore-unused */ $request ) {

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

Loading history...
152
		if ( ! wc_rest_check_post_permissions( $this->post_type, 'batch' ) ) {
153
			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() ) );
154
		}
155
156
		return true;
157
	}
158
159
	/**
160
	 * Get a single item.
161
	 *
162
	 * @param \WP_REST_Request $request Full details about the request.
163
	 * @return \WP_Error|\WP_REST_Response
164
	 */
165
	public function get_item( $request ) {
166
		$object = $this->get_object( (int) $request['id'] );
167
168
		if ( ! $object || 0 === $object->get_id() ) {
169
			return new \WP_Error( "woocommerce_rest_{$this->post_type}_invalid_id", __( 'Invalid ID.', 'woocommerce' ), array( 'status' => 404 ) );
170
		}
171
172
		$data     = $this->prepare_object_for_response( $object, $request );
0 ignored issues
show
Bug introduced by
It seems like $object can also be of type true; however, parameter $object of WooCommerce\RestApi\Cont...e_object_for_response() does only seem to accept WC_Data, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

172
		$data     = $this->prepare_object_for_response( /** @scrutinizer ignore-type */ $object, $request );
Loading history...
173
		$response = rest_ensure_response( $data );
174
175
		return $response;
176
	}
177
178
	/**
179
	 * Save an object data.
180
	 *
181
	 * @since  3.0.0
182
	 * @param  \WP_REST_Request $request  Full details about the request.
183
	 * @param  bool             $creating If is creating a new object.
184
	 * @return \WC_Data|\WP_Error
185
	 */
186
	protected function save_object( $request, $creating = false ) {
187
		try {
188
			$object = $this->prepare_object_for_database( $request, $creating );
189
190
			if ( is_wp_error( $object ) ) {
191
				return $object;
192
			}
193
194
			$object->save();
195
196
			return $this->get_object( $object->get_id() );
197
		} catch ( \WC_Data_Exception $e ) {
198
			return new \WP_Error( $e->getErrorCode(), $e->getMessage(), $e->getErrorData() );
199
		} catch ( \WC_REST_Exception $e ) {
200
			return new \WP_Error( $e->getErrorCode(), $e->getMessage(), array( 'status' => $e->getCode() ) );
201
		}
202
	}
203
204
	/**
205
	 * Create a single item.
206
	 *
207
	 * @param \WP_REST_Request $request Full details about the request.
208
	 * @return \WP_Error|\WP_REST_Response
209
	 */
210
	public function create_item( $request ) {
211
		if ( ! empty( $request['id'] ) ) {
212
			/* translators: %s: post type */
213
			return new \WP_Error( "woocommerce_rest_{$this->post_type}_exists", sprintf( __( 'Cannot create existing %s.', 'woocommerce' ), $this->post_type ), array( 'status' => 400 ) );
214
		}
215
216
		$object = $this->save_object( $request, true );
217
218
		if ( is_wp_error( $object ) ) {
219
			return $object;
220
		}
221
222
		try {
223
			$this->update_additional_fields_for_object( $object, $request );
0 ignored issues
show
Bug introduced by
$object of type WC_Data|WP_Error is incompatible with the type array expected by parameter $object of WP_REST_Controller::upda...nal_fields_for_object(). ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

223
			$this->update_additional_fields_for_object( /** @scrutinizer ignore-type */ $object, $request );
Loading history...
224
		} catch ( \WC_Data_Exception $e ) {
225
			$object->delete();
0 ignored issues
show
Bug introduced by
The method delete() does not exist on WP_Error. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

225
			$object->/** @scrutinizer ignore-call */ 
226
            delete();

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
226
			return new \WP_Error( $e->getErrorCode(), $e->getMessage(), $e->getErrorData() );
227
		} catch ( \WC_REST_Exception $e ) {
228
			$object->delete();
229
			return new \WP_Error( $e->getErrorCode(), $e->getMessage(), array( 'status' => $e->getCode() ) );
230
		}
231
232
		/**
233
		 * Fires after a single object is created or updated via the REST API.
234
		 *
235
		 * @param \WC_Data         $object    Inserted object.
236
		 * @param \WP_REST_Request $request   Request object.
237
		 * @param boolean         $creating  True when creating object, false when updating.
238
		 */
239
		do_action( "woocommerce_rest_insert_{$this->post_type}_object", $object, $request, true );
240
241
		$request->set_param( 'context', 'edit' );
242
		$response = $this->prepare_object_for_response( $object, $request );
0 ignored issues
show
Bug introduced by
It seems like $object can also be of type WP_Error; however, parameter $object of WooCommerce\RestApi\Cont...e_object_for_response() does only seem to accept WC_Data, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

242
		$response = $this->prepare_object_for_response( /** @scrutinizer ignore-type */ $object, $request );
Loading history...
243
		$response = rest_ensure_response( $response );
244
		$response->set_status( 201 );
245
		$response->header( 'Location', rest_url( sprintf( '/%s/%s/%d', $this->namespace, $this->rest_base, $object->get_id() ) ) );
0 ignored issues
show
Bug introduced by
The method get_id() does not exist on WP_Error. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

245
		$response->header( 'Location', rest_url( sprintf( '/%s/%s/%d', $this->namespace, $this->rest_base, $object->/** @scrutinizer ignore-call */ get_id() ) ) );

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
246
247
		return $response;
248
	}
249
250
	/**
251
	 * Update a single post.
252
	 *
253
	 * @param \WP_REST_Request $request Full details about the request.
254
	 * @return \WP_Error|\WP_REST_Response
255
	 */
256
	public function update_item( $request ) {
257
		$object = $this->get_object( (int) $request['id'] );
258
259
		if ( ! $object || 0 === $object->get_id() ) {
260
			return new \WP_Error( "woocommerce_rest_{$this->post_type}_invalid_id", __( 'Invalid ID.', 'woocommerce' ), array( 'status' => 404 ) );
261
		}
262
263
		$object = $this->save_object( $request, false );
264
265
		if ( is_wp_error( $object ) ) {
266
			return $object;
267
		}
268
269
		try {
270
			$this->update_additional_fields_for_object( $object, $request );
0 ignored issues
show
Bug introduced by
$object of type WC_Data|WP_Error is incompatible with the type array expected by parameter $object of WP_REST_Controller::upda...nal_fields_for_object(). ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

270
			$this->update_additional_fields_for_object( /** @scrutinizer ignore-type */ $object, $request );
Loading history...
271
		} catch ( \WC_Data_Exception $e ) {
272
			return new \WP_Error( $e->getErrorCode(), $e->getMessage(), $e->getErrorData() );
273
		} catch ( \WC_REST_Exception $e ) {
274
			return new \WP_Error( $e->getErrorCode(), $e->getMessage(), array( 'status' => $e->getCode() ) );
275
		}
276
277
		/**
278
		 * Fires after a single object is created or updated via the REST API.
279
		 *
280
		 * @param \WC_Data         $object    Inserted object.
281
		 * @param \WP_REST_Request $request   Request object.
282
		 * @param boolean         $creating  True when creating object, false when updating.
283
		 */
284
		do_action( "woocommerce_rest_insert_{$this->post_type}_object", $object, $request, false );
285
286
		$request->set_param( 'context', 'edit' );
287
		$response = $this->prepare_object_for_response( $object, $request );
0 ignored issues
show
Bug introduced by
It seems like $object can also be of type WP_Error; however, parameter $object of WooCommerce\RestApi\Cont...e_object_for_response() does only seem to accept WC_Data, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

287
		$response = $this->prepare_object_for_response( /** @scrutinizer ignore-type */ $object, $request );
Loading history...
288
		return rest_ensure_response( $response );
289
	}
290
291
	/**
292
	 * Prepare objects query.
293
	 *
294
	 * @since  3.0.0
295
	 * @param  \WP_REST_Request $request Full details about the request.
296
	 * @return array
297
	 */
298
	protected function prepare_objects_query( $request ) {
299
		$args                        = array();
300
		$args['offset']              = $request['offset'];
301
		$args['order']               = $request['order'];
302
		$args['orderby']             = $request['orderby'];
303
		$args['paged']               = $request['page'];
304
		$args['post__in']            = $request['include'];
305
		$args['post__not_in']        = $request['exclude'];
306
		$args['posts_per_page']      = $request['per_page'];
307
		$args['name']                = $request['slug'];
308
		$args['post_parent__in']     = $request['parent'];
309
		$args['post_parent__not_in'] = $request['parent_exclude'];
310
		$args['s']                   = $request['search'];
311
		$args['fields']              = 'ids';
312
313
		if ( 'date' === $args['orderby'] ) {
314
			$args['orderby'] = 'date ID';
315
		}
316
317
		$args['date_query'] = array();
318
319
		// Set before into date query. Date query must be specified as an array of an array.
320
		if ( isset( $request['before'] ) ) {
321
			$args['date_query'][0]['before'] = $request['before'];
322
		}
323
324
		// Set after into date query. Date query must be specified as an array of an array.
325
		if ( isset( $request['after'] ) ) {
326
			$args['date_query'][0]['after'] = $request['after'];
327
		}
328
329
		// Set date query colummn. Defaults to post_date.
330
		if ( isset( $request['date_column'] ) && ! empty( $args['date_query'][0] ) ) {
331
			$args['date_query'][0]['column'] = 'post_' . $request['date_column'];
332
		}
333
334
		// Force the post_type argument, since it's not a user input variable.
335
		$args['post_type'] = $this->post_type;
336
337
		/**
338
		 * Filter the query arguments for a request.
339
		 *
340
		 * Enables adding extra arguments or setting defaults for a post
341
		 * collection request.
342
		 *
343
		 * @param array            $args    Key value array of query var to query value.
344
		 * @param \WP_REST_Request $request The request used.
345
		 */
346
		$args = apply_filters( "woocommerce_rest_{$this->post_type}_object_query", $args, $request );
347
348
		return $this->prepare_items_query( $args, $request );
349
	}
350
351
	/**
352
	 * Get objects.
353
	 *
354
	 * @since  3.0.0
355
	 * @param  array $query_args Query args.
356
	 * @return array
357
	 */
358
	protected function get_objects( $query_args ) {
359
		$query  = new \WP_Query();
360
		$result = $query->query( $query_args );
361
362
		$total_posts = $query->found_posts;
363
		if ( $total_posts < 1 ) {
364
			// Out-of-bounds, run the query again without LIMIT for total count.
365
			unset( $query_args['paged'] );
366
			$count_query = new \WP_Query();
367
			$count_query->query( $query_args );
368
			$total_posts = $count_query->found_posts;
369
		}
370
371
		return array(
372
			'objects' => array_map( array( $this, 'get_object' ), $result ),
373
			'total'   => (int) $total_posts,
374
			'pages'   => (int) ceil( $total_posts / (int) $query->query_vars['posts_per_page'] ),
375
		);
376
	}
377
378
	/**
379
	 * Get a collection of posts.
380
	 *
381
	 * @param \WP_REST_Request $request Full details about the request.
382
	 * @return \WP_REST_Response
383
	 */
384
	public function get_items( $request ) {
385
		$query_args    = $this->prepare_objects_query( $request );
386
		$query_results = $this->get_objects( $query_args );
387
388
		$objects = array();
389
		foreach ( $query_results['objects'] as $object ) {
390
			if ( ! wc_rest_check_post_permissions( $this->post_type, 'read', $object->get_id() ) ) {
391
				continue;
392
			}
393
394
			$data      = $this->prepare_object_for_response( $object, $request );
395
			$objects[] = $this->prepare_response_for_collection( $data );
396
		}
397
398
		$page      = (int) $query_args['paged'];
399
		$max_pages = $query_results['pages'];
400
401
		$response = rest_ensure_response( $objects );
402
		$response->header( 'X-WP-Total', $query_results['total'] );
403
		$response->header( 'X-WP-TotalPages', (int) $max_pages );
404
405
		$base          = $this->rest_base;
406
		$attrib_prefix = '(?P<';
407
		if ( strpos( $base, $attrib_prefix ) !== false ) {
408
			$attrib_names = array();
409
			preg_match( '/\(\?P<[^>]+>.*\)/', $base, $attrib_names, PREG_OFFSET_CAPTURE );
410
			foreach ( $attrib_names as $attrib_name_match ) {
411
				$beginning_offset = strlen( $attrib_prefix );
412
				$attrib_name_end  = strpos( $attrib_name_match[0], '>', $attrib_name_match[1] );
413
				$attrib_name      = substr( $attrib_name_match[0], $beginning_offset, $attrib_name_end - $beginning_offset );
414
				if ( isset( $request[ $attrib_name ] ) ) {
415
					$base = str_replace( "(?P<$attrib_name>[\d]+)", $request[ $attrib_name ], $base );
416
				}
417
			}
418
		}
419
		$base = add_query_arg( $request->get_query_params(), rest_url( sprintf( '/%s/%s', $this->namespace, $base ) ) );
420
421
		if ( $page > 1 ) {
422
			$prev_page = $page - 1;
423
			if ( $prev_page > $max_pages ) {
424
				$prev_page = $max_pages;
425
			}
426
			$prev_link = add_query_arg( 'page', $prev_page, $base );
427
			$response->link_header( 'prev', $prev_link );
428
		}
429
		if ( $max_pages > $page ) {
430
			$next_page = $page + 1;
431
			$next_link = add_query_arg( 'page', $next_page, $base );
432
			$response->link_header( 'next', $next_link );
433
		}
434
435
		return $response;
436
	}
437
438
	/**
439
	 * Delete a single item.
440
	 *
441
	 * @param \WP_REST_Request $request Full details about the request.
442
	 * @return \WP_REST_Response|\WP_Error
443
	 */
444
	public function delete_item( $request ) {
445
		$force  = (bool) $request['force'];
446
		$object = $this->get_object( (int) $request['id'] );
447
		$result = false;
448
449
		if ( ! $object || 0 === $object->get_id() ) {
450
			return new \WP_Error( "woocommerce_rest_{$this->post_type}_invalid_id", __( 'Invalid ID.', 'woocommerce' ), array( 'status' => 404 ) );
451
		}
452
453
		$supports_trash = $this->supports_trash( $object );
0 ignored issues
show
Bug introduced by
It seems like $object can also be of type true; however, parameter $object of WooCommerce\RestApi\Cont...oller::supports_trash() does only seem to accept object, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

453
		$supports_trash = $this->supports_trash( /** @scrutinizer ignore-type */ $object );
Loading history...
454
455
		if ( ! wc_rest_check_post_permissions( $this->post_type, 'delete', $object->get_id() ) ) {
456
			/* translators: %s: post type */
457
			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() ) );
458
		}
459
460
		$request->set_param( 'context', 'edit' );
461
		$previous = $this->prepare_object_for_response( $object, $request );
0 ignored issues
show
Bug introduced by
It seems like $object can also be of type true; however, parameter $object of WooCommerce\RestApi\Cont...e_object_for_response() does only seem to accept WC_Data, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

461
		$previous = $this->prepare_object_for_response( /** @scrutinizer ignore-type */ $object, $request );
Loading history...
462
463
		// If we're forcing, then delete permanently.
464
		if ( $force ) {
465
			$object->delete( true );
466
			$result = 0 === $object->get_id();
467
		} else {
468
			// If we don't support trashing for this type, error out.
469
			if ( ! $supports_trash ) {
470
				/* translators: %s: post type */
471
				return new \WP_Error( 'woocommerce_rest_trash_not_supported', sprintf( __( 'The %s does not support trashing.', 'woocommerce' ), $this->post_type ), array( 'status' => 501 ) );
472
			}
473
474
			// Otherwise, only trash if we haven't already.
475
			if ( is_callable( array( $object, 'get_status' ) ) && 'trash' === $object->get_status() ) {
0 ignored issues
show
Bug introduced by
The method get_status() does not exist on WC_Data. It seems like you code against a sub-type of WC_Data such as WC_Product or WC_Abstract_Order or WC_Webhook. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

475
			if ( is_callable( array( $object, 'get_status' ) ) && 'trash' === $object->/** @scrutinizer ignore-call */ get_status() ) {
Loading history...
476
				/* translators: %s: post type */
477
				return new \WP_Error( 'woocommerce_rest_already_trashed', sprintf( __( 'The %s has already been deleted.', 'woocommerce' ), $this->post_type ), array( 'status' => 410 ) );
478
			} else {
479
				$object->delete();
480
				$result = is_callable( array( $object, 'get_status' ) ) ? 'trash' === $object->get_status() : true;
481
			}
482
		}
483
484
		if ( ! $result ) {
485
			/* translators: %s: post type */
486
			return new \WP_Error( 'woocommerce_rest_cannot_delete', sprintf( __( 'The %s cannot be deleted.', 'woocommerce' ), $this->post_type ), array( 'status' => 500 ) );
487
		}
488
489
		$response = new \WP_REST_Response();
490
		$response->set_data(
491
			array(
492
				'deleted'  => true,
493
				'previous' => $previous->get_data(),
494
			)
495
		);
496
497
		/**
498
		 * Fires after a single object is deleted or trashed via the REST API.
499
		 *
500
		 * @param \WC_Data          $object   The deleted or trashed object.
501
		 * @param \WP_REST_Response $response The response data.
502
		 * @param \WP_REST_Request  $request  The request sent to the API.
503
		 */
504
		do_action( "woocommerce_rest_delete_{$this->post_type}_object", $object, $response, $request );
505
506
		return $response;
507
	}
508
509
	/**
510
	 * Can this object be trashed?
511
	 *
512
	 * @param  object $object Object to check.
513
	 * @return boolean
514
	 */
515
	protected function supports_trash( $object ) {
516
		$supports_trash = EMPTY_TRASH_DAYS > 0;
517
518
		/**
519
		 * Filter whether an object is trashable.
520
		 *
521
		 * Return false to disable trash support for the object.
522
		 *
523
		 * @param boolean $supports_trash Whether the object type support trashing.
524
		 * @param \WC_Data $object         The object being considered for trashing support.
525
		 */
526
		return apply_filters( "woocommerce_rest_{$this->post_type}_object_trashable", $supports_trash, $object );
527
	}
528
529
	/**
530
	 * Prepare links for the request.
531
	 *
532
	 * @param \WC_Data         $object  Object data.
533
	 * @param \WP_REST_Request $request Request object.
534
	 * @return array                   Links for the given post.
535
	 */
536
	protected function prepare_links( $object, $request ) {
537
		$links = array(
538
			'self'       => array(
539
				'href' => rest_url( sprintf( '/%s/%s/%d', $this->namespace, $this->rest_base, $object->get_id() ) ),
540
			),
541
			'collection' => array(
542
				'href' => rest_url( sprintf( '/%s/%s', $this->namespace, $this->rest_base ) ),
543
			),
544
		);
545
546
		return $links;
547
	}
548
549
	/**
550
	 * Get the query params for collections of attachments.
551
	 *
552
	 * @return array
553
	 */
554
	public function get_collection_params() {
555
		$params                       = array();
556
		$params['context']            = $this->get_context_param();
557
		$params['context']['default'] = 'view';
558
559
		$params['page'] = array(
560
			'description'       => __( 'Current page of the collection.', 'woocommerce' ),
561
			'type'              => 'integer',
562
			'default'           => 1,
563
			'sanitize_callback' => 'absint',
564
			'validate_callback' => 'rest_validate_request_arg',
565
			'minimum'           => 1,
566
		);
567
568
		$params['per_page'] = array(
569
			'description'       => __( 'Maximum number of items to be returned in result set.', 'woocommerce' ),
570
			'type'              => 'integer',
571
			'default'           => 10,
572
			'minimum'           => 1,
573
			'maximum'           => 100,
574
			'sanitize_callback' => 'absint',
575
			'validate_callback' => 'rest_validate_request_arg',
576
		);
577
578
		$params['search'] = array(
579
			'description'       => __( 'Limit results to those matching a string.', 'woocommerce' ),
580
			'type'              => 'string',
581
			'sanitize_callback' => 'sanitize_text_field',
582
			'validate_callback' => 'rest_validate_request_arg',
583
		);
584
585
		$params['after'] = array(
586
			'description'       => __( 'Limit response to resources created after a given ISO8601 compliant date.', 'woocommerce' ),
587
			'type'              => 'string',
588
			'format'            => 'date-time',
589
			'validate_callback' => 'rest_validate_request_arg',
590
		);
591
592
		$params['before'] = array(
593
			'description'       => __( 'Limit response to resources created before a given ISO8601 compliant date.', 'woocommerce' ),
594
			'type'              => 'string',
595
			'format'            => 'date-time',
596
			'validate_callback' => 'rest_validate_request_arg',
597
		);
598
599
		$params['date_column'] = array(
600
			'description'       => __( 'When limiting response using after/before, which date column to compare against.', 'woocommerce' ),
601
			'type'              => 'string',
602
			'default'           => 'date',
603
			'enum'              => array(
604
				'date',
605
				'date_gmt',
606
				'modified',
607
				'modified_gmt',
608
			),
609
			'validate_callback' => 'rest_validate_request_arg',
610
		);
611
612
		$params['modified_before'] = array(
613
			'description'       => __( 'Limit response to resources modified before a given ISO8601 compliant date.', 'woocommerce' ),
614
			'type'              => 'string',
615
			'format'            => 'date-time',
616
			'validate_callback' => 'rest_validate_request_arg',
617
		);
618
619
		$params['exclude'] = array(
620
			'description'       => __( 'Ensure result set excludes specific IDs.', 'woocommerce' ),
621
			'type'              => 'array',
622
			'items'             => array(
623
				'type' => 'integer',
624
			),
625
			'default'           => array(),
626
			'sanitize_callback' => 'wp_parse_id_list',
627
		);
628
629
		$params['include'] = array(
630
			'description'       => __( 'Limit result set to specific ids.', 'woocommerce' ),
631
			'type'              => 'array',
632
			'items'             => array(
633
				'type' => 'integer',
634
			),
635
			'default'           => array(),
636
			'sanitize_callback' => 'wp_parse_id_list',
637
		);
638
639
		$params['offset'] = array(
640
			'description'       => __( 'Offset the result set by a specific number of items.', 'woocommerce' ),
641
			'type'              => 'integer',
642
			'sanitize_callback' => 'absint',
643
			'validate_callback' => 'rest_validate_request_arg',
644
		);
645
646
		$params['order'] = array(
647
			'description'       => __( 'Order sort attribute ascending or descending.', 'woocommerce' ),
648
			'type'              => 'string',
649
			'default'           => 'desc',
650
			'enum'              => array( 'asc', 'desc' ),
651
			'validate_callback' => 'rest_validate_request_arg',
652
		);
653
654
		$params['orderby'] = array(
655
			'description'       => __( 'Sort collection by object attribute.', 'woocommerce' ),
656
			'type'              => 'string',
657
			'default'           => 'date',
658
			'enum'              => array(
659
				'date',
660
				'modified',
661
				'id',
662
				'include',
663
				'title',
664
				'slug',
665
			),
666
			'validate_callback' => 'rest_validate_request_arg',
667
		);
668
669
		if ( $this->hierarchical ) {
670
			$params['parent'] = array(
671
				'description'       => __( 'Limit result set to those of particular parent IDs.', 'woocommerce' ),
672
				'type'              => 'array',
673
				'items'             => array(
674
					'type' => 'integer',
675
				),
676
				'sanitize_callback' => 'wp_parse_id_list',
677
				'default'           => array(),
678
			);
679
680
			$params['parent_exclude'] = array(
681
				'description'       => __( 'Limit result set to all items except those of a particular parent ID.', 'woocommerce' ),
682
				'type'              => 'array',
683
				'items'             => array(
684
					'type' => 'integer',
685
				),
686
				'sanitize_callback' => 'wp_parse_id_list',
687
				'default'           => array(),
688
			);
689
		}
690
691
		/**
692
		 * Filter collection parameters for the posts controller.
693
		 *
694
		 * The dynamic part of the filter `$this->post_type` refers to the post
695
		 * type slug for the controller.
696
		 *
697
		 * This filter registers the collection parameter, but does not map the
698
		 * collection parameter to an internal \WP_Query parameter. Use the
699
		 * `rest_{$this->post_type}_query` filter to set \WP_Query parameters.
700
		 *
701
		 * @param array        $query_params JSON Schema-formatted collection parameters.
702
		 * @param \WP_Post_Type $post_type    Post type object.
703
		 */
704
		return apply_filters( "rest_{$this->post_type}_collection_params", $params, $this->post_type );
705
	}
706
707
	/**
708
	 * Determine the allowed query_vars for a get_items() response and
709
	 * prepare for \WP_Query.
710
	 *
711
	 * @param array            $prepared_args Prepared arguments.
712
	 * @param \WP_REST_Request $request Request object.
713
	 * @return array           $query_args
714
	 */
715
	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. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-unused  annotation

715
	protected function prepare_items_query( $prepared_args = array(), /** @scrutinizer ignore-unused */ $request = null ) {

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

Loading history...
716
		$valid_vars = array_flip( $this->get_allowed_query_vars() );
717
		$query_args = array();
718
		foreach ( $valid_vars as $var => $index ) {
719
			if ( isset( $prepared_args[ $var ] ) ) {
720
				/**
721
				 * Filter the query_vars used in `get_items` for the constructed query.
722
				 *
723
				 * The dynamic portion of the hook name, $var, refers to the query_var key.
724
				 *
725
				 * @param mixed $prepared_args[ $var ] The query_var value.
726
				 */
727
				$query_args[ $var ] = apply_filters( "woocommerce_rest_query_var_{$var}", $prepared_args[ $var ] );
728
			}
729
		}
730
731
		$query_args['ignore_sticky_posts'] = true;
732
733
		if ( 'include' === $query_args['orderby'] ) {
734
			$query_args['orderby'] = 'post__in';
735
		} elseif ( 'id' === $query_args['orderby'] ) {
736
			$query_args['orderby'] = 'ID'; // ID must be capitalized.
737
		} elseif ( 'slug' === $query_args['orderby'] ) {
738
			$query_args['orderby'] = 'name';
739
		}
740
741
		return $query_args;
742
	}
743
744
	/**
745
	 * Get all the WP Query vars that are allowed for the API request.
746
	 *
747
	 * @return array
748
	 */
749
	protected function get_allowed_query_vars() {
750
		global $wp;
751
752
		/**
753
		 * Filter the publicly allowed query vars.
754
		 *
755
		 * Allows adjusting of the default query vars that are made public.
756
		 *
757
		 * @param array  Array of allowed \WP_Query query vars.
758
		 */
759
		$valid_vars = apply_filters( 'query_vars', $wp->public_query_vars );
760
761
		$post_type_obj = get_post_type_object( $this->post_type );
762
		if ( current_user_can( $post_type_obj->cap->edit_posts ) ) {
763
			/**
764
			 * Filter the allowed 'private' query vars for authorized users.
765
			 *
766
			 * If the user has the `edit_posts` capability, we also allow use of
767
			 * private query parameters, which are only undesirable on the
768
			 * frontend, but are safe for use in query strings.
769
			 *
770
			 * To disable anyway, use
771
			 * `add_filter( 'woocommerce_rest_private_query_vars', '__return_empty_array' );`
772
			 *
773
			 * @param array $private_query_vars Array of allowed query vars for authorized users.
774
			 * }
775
			 */
776
			$private    = apply_filters( 'woocommerce_rest_private_query_vars', $wp->private_query_vars );
777
			$valid_vars = array_merge( $valid_vars, $private );
778
		}
779
		// Define our own in addition to WP's normal vars.
780
		$rest_valid = array(
781
			'date_query',
782
			'ignore_sticky_posts',
783
			'offset',
784
			'post__in',
785
			'post__not_in',
786
			'post_parent',
787
			'post_parent__in',
788
			'post_parent__not_in',
789
			'posts_per_page',
790
			'meta_query',
791
			'tax_query',
792
			'meta_key',
793
			'meta_value',
794
			'meta_compare',
795
			'meta_value_num',
796
		);
797
		$valid_vars = array_merge( $valid_vars, $rest_valid );
798
799
		/**
800
		 * Filter allowed query vars for the REST API.
801
		 *
802
		 * This filter allows you to add or remove query vars from the final allowed
803
		 * list for all requests, including unauthenticated ones. To alter the
804
		 * vars for editors only.
805
		 *
806
		 * @param array {
807
		 *    Array of allowed \WP_Query query vars.
808
		 *
809
		 *    @param string $allowed_query_var The query var to allow.
810
		 * }
811
		 */
812
		$valid_vars = apply_filters( 'woocommerce_rest_query_vars', $valid_vars );
813
814
		return $valid_vars;
815
	}
816
817
	/**
818
	 * Add meta query.
819
	 *
820
	 * @since 3.0.0
821
	 * @param array $args       Query args.
822
	 * @param array $meta_query Meta query.
823
	 * @return array
824
	 */
825
	protected function add_meta_query( $args, $meta_query ) {
826
		if ( empty( $args['meta_query'] ) ) {
827
			$args['meta_query'] = []; // phpcs:ignore
828
		}
829
830
		$args['meta_query'][] = $meta_query;
831
832
		return $args['meta_query'];
833
	}
834
}
835