Completed
Pull Request — master (#11561)
by
unknown
07:41
created

WC_REST_Product_Reviews_Controller   C

Complexity

Total Complexity 61

Size/Duplication

Total Lines 571
Duplicated Lines 29.42 %

Coupling/Cohesion

Components 1
Dependencies 1

Importance

Changes 5
Bugs 1 Features 1
Metric Value
c 5
b 1
f 1
dl 168
loc 571
rs 6.018
wmc 61
lcom 1
cbo 1

18 Methods

Rating   Name   Duplication   Size   Complexity  
A register_routes() 66 66 1
A get_items_permissions_check() 7 7 2
A get_item_permissions_check() 9 9 3
A create_item_permissions_check() 0 7 3
A update_item_permissions_check() 0 7 3
A delete_item_permissions_check() 0 7 3
A batch_items_permissions_check() 0 6 2
A get_items() 3 17 3
B get_item() 6 19 5
B create_item() 3 47 4
C update_item() 6 42 7
C delete_item() 3 51 10
A batch_items() 0 21 4
B prepare_item_for_response() 0 29 2
B prepare_item_for_database() 0 25 6
A prepare_links() 17 17 1
A get_item_schema() 48 48 1
A get_collection_params() 0 5 1

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_Product_Reviews_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_Product_Reviews_Controller, and based on these observations, apply Extract Interface, too.

1
<?php
2
/**
3
 * REST API Product Reviews Controller.
4
 *
5
 * Handles requests to /products/<product_id>/reviews.
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 Product Reviews Controller Class.
19
 *
20
 * @package WooCommerce/API
21
 * @extends WC_REST_Controller
22
 */
23
class WC_REST_Product_Reviews_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 = 'products/(?P<product_id>[\d]+)/reviews';
38
39
	/**
40
	 * Register the routes for product reviews.
41
	 */
42 View Code Duplication
	public function register_routes() {
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...
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
					'review' => array(
56
						'required' => true,
57
					),
58
					'name' => array(
59
						'required' => true,
60
					),
61
					'email' => array(
62
						'required' => true,
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' => __( 'Whether to bypass trash and force deletion.', 'woocommerce' ),
92
					),
93
				),
94
			),
95
			'schema' => array( $this, 'get_public_item_schema' ),
96
		) );
97
98
		register_rest_route( $this->namespace, '/' . $this->rest_base . '/batch', array(
99
			array(
100
				'methods'             => WP_REST_Server::EDITABLE,
101
				'callback'            => array( $this, 'batch_items' ),
102
				'permission_callback' => array( $this, 'batch_items_permissions_check' ),
103
				'args'                => $this->get_endpoint_args_for_item_schema( WP_REST_Server::EDITABLE ),
104
			),
105
			'schema' => array( $this, 'get_public_batch_schema' ),
106
		) );
107
	}
108
109
	/**
110
	 * Check whether a given request has permission to read webhook deliveries.
111
	 *
112
	 * @param  WP_REST_Request $request Full details about the request.
113
	 * @return WP_Error|boolean
114
	 */
115 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...
116
		if ( ! wc_rest_check_post_permissions( 'product', 'read' ) ) {
117
			return new WP_Error( 'woocommerce_rest_cannot_view', __( 'Sorry, you cannot list resources.', 'woocommerce' ), array( 'status' => rest_authorization_required_code() ) );
118
		}
119
120
		return true;
121
	}
122
123
	/**
124
	 * Check if a given request has access to read a product review.
125
	 *
126
	 * @param  WP_REST_Request $request Full details about the request.
127
	 * @return WP_Error|boolean
128
	 */
129 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...
130
		$post = get_post( (int) $request['product_id'] );
131
132
		if ( $post && ! wc_rest_check_post_permissions( 'product', 'read', $post->ID ) ) {
133
			return new WP_Error( 'woocommerce_rest_cannot_view', __( 'Sorry, you cannot view this resource.', 'woocommerce' ), array( 'status' => rest_authorization_required_code() ) );
134
		}
135
136
		return true;
137
	}
138
139
	/**
140
	 * Check if a given request has access to create a new product review.
141
	 *
142
	 * @param  WP_REST_Request $request Full details about the request.
143
	 * @return WP_Error|boolean
144
	 */
145
	public function create_item_permissions_check( $request ) {
146
		$post = get_post( (int) $request['product_id'] );
147
		if ( $post && ! wc_rest_check_post_permissions( 'product', 'create', $post->ID ) ) {
148
			return new WP_Error( 'woocommerce_rest_cannot_create', __( 'Sorry, you cannot create new resource.', 'woocommerce' ), array( 'status' => rest_authorization_required_code() ) );
149
		}
150
		return true;
151
	}
152
153
	/**
154
	 * Check if a given request has access to update a product review.
155
	 *
156
	 * @param  WP_REST_Request $request Full details about the request.
157
	 * @return WP_Error|boolean
158
	 */
159
	public function update_item_permissions_check( $request ) {
160
		$post = get_post( (int) $request['product_id'] );
161
		if ( $post && ! wc_rest_check_post_permissions( 'product', 'edit', $post->ID ) ) {
162
			return new WP_Error( 'woocommerce_rest_cannot_edit', __( 'Sorry, you cannot edit resource.', 'woocommerce' ), array( 'status' => rest_authorization_required_code() ) );
163
		}
164
		return true;
165
	}
166
167
	/**
168
	 * Check if a given request has access to delete a product review.
169
	 *
170
	 * @param  WP_REST_Request $request Full details about the request.
171
	 * @return WP_Error|boolean
172
	 */
173
	public function delete_item_permissions_check( $request ) {
174
		$post = get_post( (int) $request['product_id'] );
175
		if ( $post && ! wc_rest_check_post_permissions( 'product', 'delete', $post->ID ) ) {
176
			return new WP_Error( 'woocommerce_rest_cannot_edit', __( 'Sorry, you cannot delete product reviews.', 'woocommerce' ), array( 'status' => rest_authorization_required_code() ) );
177
		}
178
		return true;
179
	}
180
181
	/**
182
	 * Check if a given request has access to batch manage product reviews.
183
	 *
184
	 * @param  WP_REST_Request $request Full details about the request.
185
	 * @return WP_Error|boolean
186
	 */
187
	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...
188
		if ( ! wc_rest_check_post_permissions( 'product', 'batch' ) ) {
189
			return new WP_Error( 'woocommerce_rest_cannot_edit', __( 'Sorry, you cannot batch manipulate product reviews.', 'woocommerce' ), array( 'status' => rest_authorization_required_code() ) );
190
		}
191
		return true;
192
	}
193
194
	/**
195
	 * Get all reviews from a product.
196
	 *
197
	 * @param WP_REST_Request $request
198
	 * @return array
199
	 */
200
	public function get_items( $request ) {
201
		$product_id = (int) $request['product_id'];
202
203 View Code Duplication
		if ( 'product' !== get_post_type( $product_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...
204
			return new WP_Error( 'woocommerce_rest_product_invalid_id', __( 'Invalid product ID.', 'woocommerce' ), array( 'status' => 404 ) );
205
		}
206
207
		$reviews = get_approved_comments( $product_id );
208
		$data    = array();
209
		foreach ( $reviews as $review_data ) {
210
			$review = $this->prepare_item_for_response( $review_data, $request );
211
			$review = $this->prepare_response_for_collection( $review );
212
			$data[] = $review;
213
		}
214
215
		return rest_ensure_response( $data );
216
	}
217
218
	/**
219
	 * Get a single product review.
220
	 *
221
	 * @param WP_REST_Request $request Full details about the request.
222
	 * @return WP_Error|WP_REST_Response
223
	 */
224
	public function get_item( $request ) {
225
		$id         = (int) $request['id'];
226
		$product_id = (int) $request['product_id'];
227
228 View Code Duplication
		if ( 'product' !== get_post_type( $product_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...
229
			return new WP_Error( 'woocommerce_rest_product_invalid_id', __( 'Invalid product ID.', 'woocommerce' ), array( 'status' => 404 ) );
230
		}
231
232
		$review = get_comment( $id );
233
234 View Code Duplication
		if ( empty( $id ) || empty( $review ) || intval( $review->comment_post_ID ) !== $product_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...
235
			return new WP_Error( 'woocommerce_rest_invalid_id', __( 'Invalid resource ID.', 'woocommerce' ), array( 'status' => 404 ) );
236
		}
237
238
		$delivery = $this->prepare_item_for_response( $review, $request );
239
		$response = rest_ensure_response( $delivery );
240
241
		return $response;
242
	}
243
244
245
	/**
246
	 * Create a product review.
247
	 *
248
	 * @param WP_REST_Request $request Full details about the request.
249
	 * @return WP_Error|WP_REST_Response
250
	 */
251
	public function create_item( $request ) {
252
		$product_id = (int) $request['product_id'];
253
254 View Code Duplication
		if ( 'product' !== get_post_type( $product_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...
255
			return new WP_Error( 'woocommerce_rest_product_invalid_id', __( 'Invalid product ID.', 'woocommerce' ), array( 'status' => 404 ) );
256
		}
257
258
		$prepared_review = $this->prepare_item_for_database( $request );
259
260
		/**
261
		 * Filter a product review (comment) before it is inserted via the REST API.
262
		 *
263
		 * Allows modification of the comment right before it is inserted via `wp_insert_comment`.
264
		 *
265
		 * @param array           $prepared_review The prepared comment data for `wp_insert_comment`.
266
		 * @param WP_REST_Request $request          Request used to insert the comment.
267
		 */
268
		$prepared_review = apply_filters( 'rest_pre_insert_product_review', $prepared_review, $request );
269
270
		$product_review_id = wp_insert_comment( $prepared_review );
271
		if ( ! $product_review_id ) {
272
			return new WP_Error( 'rest_product_review_failed_create', __( 'Creating product review failed.' ), array( 'status' => 500 ) );
273
		}
274
275
		update_comment_meta( $product_review_id, 'rating', ( ! empty( $request['rating'] ) ? $request['rating'] : '0' ) );
276
277
		$product_review = get_comment( $product_review_id );
278
		$this->update_additional_fields_for_object( $product_review, $request );
279
280
		/**
281
		 * Fires after a single item is created or updated via the REST API.
282
		 *
283
		 * @param WP_Comment      $product_review Inserted object.
284
		 * @param WP_REST_Request $request        Request object.
285
		 * @param boolean         $creating       True when creating item, false when updating.
286
		 */
287
		do_action( "woocommerce_rest_insert_product_review", $product_review, $request, true );
288
289
		$request->set_param( 'context', 'edit' );
290
		$response = $this->prepare_item_for_response( $product_review, $request );
291
		$response = rest_ensure_response( $response );
292
		$response->set_status( 201 );
293
		$base = str_replace( '(?P<product_id>[\d]+)', $product_id, $this->rest_base );
294
		$response->header( 'Location', rest_url( sprintf( '/%s/%s/%d', $this->namespace, $base, $product_review_id ) ) );
295
296
		return $response;
297
	}
298
299
	/**
300
	 * Update a single product review.
301
	 *
302
	 * @param WP_REST_Request $request Full details about the request.
303
	 * @return WP_Error|WP_REST_Response
304
	 */
305
	public function update_item( $request ) {
306
		$product_review_id = (int) $request['id'];
307
		$product_id        = (int) $request['product_id'];
308
309 View Code Duplication
		if ( 'product' !== get_post_type( $product_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...
310
			return new WP_Error( 'woocommerce_rest_product_invalid_id', __( 'Invalid product ID.', 'woocommerce' ), array( 'status' => 404 ) );
311
		}
312
313
		$review = get_comment( $product_review_id );
314
315 View Code Duplication
		if ( empty( $product_review_id ) || empty( $review ) || intval( $review->comment_post_ID ) !== $product_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...
316
			return new WP_Error( 'woocommerce_rest_product_review_invalid_id', __( 'Invalid resource ID.', 'woocommerce' ), array( 'status' => 404 ) );
317
		}
318
319
		$prepared_review = $this->prepare_item_for_database( $request );
320
321
		$updated = wp_update_comment( $prepared_review );
322
		if ( 0 === $updated ) {
323
			return new WP_Error( 'rest_product_review_failed_edit', __( 'Updating product review failed.' ), array( 'status' => 500 ) );
324
		}
325
326
		if ( ! empty( $request['rating'] ) ) {
327
			update_comment_meta( $product_review_id, 'rating', $request['rating'] );
328
		}
329
330
		$product_review = get_comment( $product_review_id );
331
		$this->update_additional_fields_for_object( $product_review, $request );
332
333
		/**
334
		 * Fires after a single item is created or updated via the REST API.
335
		 *
336
		 * @param WP_Comment         $comment      Inserted object.
337
		 * @param WP_REST_Request $request   Request object.
338
		 * @param boolean         $creating  True when creating item, false when updating.
339
		 */
340
		do_action( "woocommerce_rest_insert_product_review", $product_review, $request, true );
341
342
		$request->set_param( 'context', 'edit' );
343
		$response = $this->prepare_item_for_response( $product_review, $request );
344
345
		return rest_ensure_response( $response );
346
	}
347
348
	/**
349
	 * Delete a product review.
350
	 *
351
	 * @param WP_REST_Request $request Full details about the request
352
	 * @return WP_Error|boolean
353
	 */
354
	public function delete_item( $request ) {
355
		$product_review_id = is_array( $request['id'] ) ? $request['id']['id'] : $request['id'];
356
		$force = isset( $request['force'] ) ? (bool) $request['force'] : false;
357
358
		$product_review = get_comment( $product_review_id );
359 View Code Duplication
		if ( empty( $product_review_id ) || empty( $product_review->comment_ID ) || empty( $product_review->comment_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...
360
			return new WP_Error( 'woocommerce_rest_product_review_invalid_id', __( 'Invalid product review ID.', 'woocommerce' ), array( 'status' => 404 ) );
361
		}
362
363
		/**
364
		 * Filter whether a product review is trashable.
365
		 *
366
		 * Return false to disable trash support for the product review.
367
		 *
368
		 * @param boolean $supports_trash        Whether the object supports trashing.
369
		 * @param WP_Post $product_review        The object being considered for trashing support.
370
		 */
371
		$supports_trash = apply_filters( 'rest_product_review_trashable', ( EMPTY_TRASH_DAYS > 0 ), $product_review );
372
373
		$request->set_param( 'context', 'edit' );
374
		$response = $this->prepare_item_for_response( $product_review, $request );
375
376
		if ( $force ) {
377
			$result = wp_delete_comment( $product_review_id, true );
378
		} else {
379
			if ( ! $supports_trash ) {
380
				return new WP_Error( 'rest_trash_not_supported', __( 'The product review does not support trashing.' ), array( 'status' => 501 ) );
381
			}
382
383
			if ( 'trash' === $product_review->comment_approved ) {
384
				return new WP_Error( 'rest_already_trashed', __( 'The comment has already been trashed.' ), array( 'status' => 410 ) );
385
			}
386
387
			$result = wp_trash_comment( $product_review->comment_ID );
388
		}
389
390
		if ( ! $result ) {
391
			return new WP_Error( 'rest_cannot_delete', __( 'The product review cannot be deleted.' ), array( 'status' => 500 ) );
392
		}
393
394
		/**
395
		 * Fires after a product review is deleted via the REST API.
396
		 *
397
		 * @param object           $product_review  The deleted item.
398
		 * @param WP_REST_Response $response        The response data.
399
		 * @param WP_REST_Request  $request         The request sent to the API.
400
		 */
401
		do_action( 'rest_delete_product_review', $product_review, $response, $request );
402
403
		return $response;
404
	}
405
406
	/**
407
	 * Bulk create, update and delete items.
408
	 *
409
	 * @since  2.7.0
410
	 * @param WP_REST_Request $request Full details about the request.
411
	 * @return array Of WP_Error or WP_REST_Response.
412
	 */
413
	public function batch_items( $request ) {
414
		$items       = array_filter( $request->get_params() );
415
		$params      = $request->get_url_params();
416
		$product_id  = $params['product_id'];
417
		$body_params = array();
418
419
		foreach ( array( 'update', 'create', 'delete' ) as $batch_type ) {
420
			if ( ! empty( $items[ $batch_type ] ) ) {
421
				$injected_items = array();
422
				foreach ( $items[ $batch_type ] as $item ) {
423
					$injected_items[] = array_merge( array( 'product_id' => $product_id ), $item );
424
				}
425
				$body_params[ $batch_type ] = $injected_items;
426
			}
427
		}
428
429
		$request = new WP_REST_Request( $request->get_method() );
430
		$request->set_body_params( $body_params );
431
432
		return parent::batch_items( $request );
433
	}
434
435
	/**
436
	 * Prepare a single product review output for response.
437
	 *
438
	 * @param WP_Comment $review Product review object.
439
	 * @param WP_REST_Request $request Request object.
440
	 * @return WP_REST_Response $response Response data.
441
	 */
442
	public function prepare_item_for_response( $review, $request ) {
443
		$data = array(
444
			'id'           => (int) $review->comment_ID,
445
			'date_created' => wc_rest_prepare_date_response( $review->comment_date_gmt ),
446
			'review'       => $review->comment_content,
447
			'rating'       => (int) get_comment_meta( $review->comment_ID, 'rating', true ),
448
			'name'         => $review->comment_author,
449
			'email'        => $review->comment_author_email,
450
			'verified'     => wc_review_is_from_verified_owner( $review->comment_ID ),
451
		);
452
453
		$context = ! empty( $request['context'] ) ? $request['context'] : 'view';
454
		$data    = $this->add_additional_fields_to_object( $data, $request );
455
		$data    = $this->filter_response_by_context( $data, $context );
456
457
		// Wrap the data in a response object.
458
		$response = rest_ensure_response( $data );
459
460
		$response->add_links( $this->prepare_links( $review, $request ) );
461
462
		/**
463
		 * Filter product reviews object returned from the REST API.
464
		 *
465
		 * @param WP_REST_Response $response The response object.
466
		 * @param WP_Comment       $review   Product review object used to create response.
467
		 * @param WP_REST_Request  $request  Request object.
468
		 */
469
		return apply_filters( 'woocommerce_rest_prepare_product_review', $response, $review, $request );
470
	}
471
472
	/**
473
	 * Prepare a single product review to be inserted into the database.
474
	 *
475
	 * @param  WP_REST_Request $request Request object.
476
	 * @return array|WP_Error  $prepared_review
477
	 */
478
	protected function prepare_item_for_database( $request ) {
479
		$prepared_review = array( 'comment_approved' => 1, 'comment_type' => 'review' );
480
481
		if ( isset( $request['id'] ) ) {
482
			$prepared_review['comment_ID'] = (int) $request['id'];
483
		}
484
485
		if ( isset( $request['review'] ) ) {
486
			$prepared_review['comment_content'] = $request['review'];
487
		}
488
489
		if ( isset( $request['product_id'] ) ) {
490
			$prepared_review['comment_post_ID'] = (int) $request['product_id'];
491
		}
492
493
		if ( isset( $request['name'] ) ) {
494
			$prepared_review['comment_author'] = $request['name'];
495
		}
496
497
		if ( isset( $request['email'] ) ) {
498
			$prepared_review['comment_author_email'] = $request['email'];
499
		}
500
501
		return apply_filters( 'rest_preprocess_product_review', $prepared_review, $request );
502
	}
503
504
	/**
505
	 * Prepare links for the request.
506
	 *
507
	 * @param WP_Comment $review Product review object.
508
	 * @param WP_REST_Request $request Request object.
509
	 * @return array Links for the given product review.
510
	 */
511 View Code Duplication
	protected function prepare_links( $review, $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...
512
		$product_id = (int) $request['product_id'];
513
		$base       = str_replace( '(?P<product_id>[\d]+)', $product_id, $this->rest_base );
514
		$links      = array(
515
			'self' => array(
516
				'href' => rest_url( sprintf( '/%s/%s/%d', $this->namespace, $base, $review->comment_ID ) ),
517
			),
518
			'collection' => array(
519
				'href' => rest_url( sprintf( '/%s/%s', $this->namespace, $base ) ),
520
			),
521
			'up' => array(
522
				'href' => rest_url( sprintf( '/%s/products/%d', $this->namespace, $product_id ) ),
523
			),
524
		);
525
526
		return $links;
527
	}
528
529
	/**
530
	 * Get the Product Review's schema, conforming to JSON Schema.
531
	 *
532
	 * @return array
533
	 */
534 View Code Duplication
	public function get_item_schema() {
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...
535
		$schema = array(
536
			'$schema'    => 'http://json-schema.org/draft-04/schema#',
537
			'title'      => 'product_review',
538
			'type'       => 'object',
539
			'properties' => array(
540
				'id' => array(
541
					'description' => __( 'Unique identifier for the resource.', 'woocommerce' ),
542
					'type'        => 'integer',
543
					'context'     => array( 'view', 'edit' ),
544
					'readonly'    => true,
545
				),
546
				'review' => array(
547
					'description' => __( 'The content of the review.', 'woocommerce' ),
548
					'type'        => 'string',
549
					'context'     => array( 'view', 'edit' ),
550
				),
551
				'date_created' => array(
552
					'description' => __( "The date the review was created, in the site's timezone.", 'woocommerce' ),
553
					'type'        => 'date-time',
554
					'context'     => array( 'view', 'edit' ),
555
				),
556
				'rating' => array(
557
					'description' => __( 'Review rating (0 to 5).', 'woocommerce' ),
558
					'type'        => 'integer',
559
					'context'     => array( 'view', 'edit' ),
560
				),
561
				'name' => array(
562
					'description' => __( 'Reviewer name.', 'woocommerce' ),
563
					'type'        => 'string',
564
					'context'     => array( 'view', 'edit' ),
565
				),
566
				'email' => array(
567
					'description' => __( 'Reviewer email.', 'woocommerce' ),
568
					'type'        => 'string',
569
					'context'     => array( 'view', 'edit' ),
570
				),
571
				'verified' => array(
572
					'description' => __( 'Shows if the reviewer bought the product or not.', 'woocommerce' ),
573
					'type'        => 'boolean',
574
					'context'     => array( 'view', 'edit' ),
575
					'readonly'    => true,
576
				),
577
			),
578
		);
579
580
		return $this->add_additional_fields_schema( $schema );
581
	}
582
583
	/**
584
	 * Get the query params for collections.
585
	 *
586
	 * @return array
587
	 */
588
	public function get_collection_params() {
589
		return array(
590
			'context' => $this->get_context_param( array( 'default' => 'view' ) ),
591
		);
592
	}
593
}
594