WC_REST_Order_Refunds_Controller::__construct()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
dl 0
loc 4
rs 10
c 0
b 0
f 0
eloc 3
nc 1
nop 0
1
<?php
2
/**
3
 * REST API Order Refunds controller
4
 *
5
 * Handles requests to the /orders/<order_id>/refunds endpoint.
6
 *
7
 * @author   WooThemes
8
 * @category API
9
 * @package  WooCommerce/API
10
 * @since    2.6.0
11
 */
12
13
if ( ! defined( 'ABSPATH' ) ) {
14
	exit;
15
}
16
17
/**
18
 * REST API Order Refunds controller class.
19
 *
20
 * @package WooCommerce/API
21
 * @extends WC_REST_Posts_Controller
22
 */
23
class WC_REST_Order_Refunds_Controller extends WC_REST_Posts_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 = 'orders/(?P<order_id>[\d]+)/refunds';
38
39
	/**
40
	 * Post type.
41
	 *
42
	 * @var string
43
	 */
44
	protected $post_type = 'shop_order_refund';
45
46
	/**
47
	 * Order refunds actions.
48
	 */
49
	public function __construct() {
50
		add_filter( "woocommerce_rest_{$this->post_type}_trashable", '__return_false' );
51
		add_filter( "woocommerce_rest_{$this->post_type}_query", array( $this, 'query_args' ), 10, 2 );
52
	}
53
54
	/**
55
	 * Register the routes for order refunds.
56
	 */
57 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...
58
		register_rest_route( $this->namespace, '/' . $this->rest_base, array(
59
			array(
60
				'methods'             => WP_REST_Server::READABLE,
61
				'callback'            => array( $this, 'get_items' ),
62
				'permission_callback' => array( $this, 'get_items_permissions_check' ),
63
				'args'                => $this->get_collection_params(),
64
			),
65
			array(
66
				'methods'             => WP_REST_Server::CREATABLE,
67
				'callback'            => array( $this, 'create_item' ),
68
				'permission_callback' => array( $this, 'create_item_permissions_check' ),
69
				'args'                => $this->get_endpoint_args_for_item_schema( WP_REST_Server::CREATABLE ),
70
			),
71
			'schema' => array( $this, 'get_public_item_schema' ),
72
		) );
73
74
		register_rest_route( $this->namespace, '/' . $this->rest_base . '/(?P<id>[\d]+)', array(
75
			array(
76
				'methods'             => WP_REST_Server::READABLE,
77
				'callback'            => array( $this, 'get_item' ),
78
				'permission_callback' => array( $this, 'get_item_permissions_check' ),
79
				'args'                => array(
80
					'context' => $this->get_context_param( array( 'default' => 'view' ) ),
81
				),
82
			),
83
			array(
84
				'methods'             => WP_REST_Server::DELETABLE,
85
				'callback'            => array( $this, 'delete_item' ),
86
				'permission_callback' => array( $this, 'delete_item_permissions_check' ),
87
				'args'                => array(
88
					'force' => array(
89
						'default'     => false,
90
						'description' => __( 'Required to be true, as resource does not support trashing.', 'woocommerce' ),
91
					),
92
					'reassign' => array(),
93
				),
94
			),
95
			'schema' => array( $this, 'get_public_item_schema' ),
96
		) );
97
	}
98
99
	/**
100
	 * Prepare a single order refund output for response.
101
	 *
102
	 * @param WP_Post $post Post object.
103
	 * @param WP_REST_Request $request Request object.
104
	 * @return WP_REST_Response $data
105
	 */
106
	public function prepare_item_for_response( $post, $request ) {
107
		global $wpdb;
108
109
		$order = wc_get_order( (int) $request['order_id'] );
110
111
		if ( ! $order ) {
112
			return new WP_Error( 'woocommerce_rest_invalid_order_id', __( 'Invalid order ID.', 'woocommerce' ), 404 );
113
		}
114
115
		$refund = wc_get_order( $post );
116
117
		if ( ! $refund || intval( $refund->post->post_parent ) !== intval( $order->id ) ) {
118
			return new WP_Error( 'woocommerce_rest_invalid_order_refund_id', __( 'Invalid order refund ID.', 'woocommerce' ), 404 );
119
		}
120
121
		$dp = $request['dp'];
122
123
		$data = array(
124
			'id'           => $refund->id,
125
			'date_created' => wc_rest_prepare_date_response( $refund->date ),
126
			'amount'       => wc_format_decimal( $refund->get_refund_amount(), $dp ),
127
			'reason'       => $refund->get_refund_reason(),
128
			'line_items'   => array(),
129
		);
130
131
		// Add line items.
132 View Code Duplication
		foreach ( $refund->get_items() as $item_id => $item ) {
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...
133
			$product      = $refund->get_product_from_item( $item );
134
			$product_id   = 0;
135
			$variation_id = 0;
136
			$product_sku  = null;
137
138
			// Check if the product exists.
139
			if ( is_object( $product ) ) {
140
				$product_id   = $product->id;
141
				$variation_id = $product->variation_id;
142
				$product_sku  = $product->get_sku();
143
			}
144
145
			$meta = new WC_Order_Item_Meta( $item, $product );
146
147
			$item_meta = array();
148
149
			$hideprefix = 'true' === $request['all_item_meta'] ? null : '_';
150
151
			foreach ( $meta->get_formatted( $hideprefix ) as $meta_key => $formatted_meta ) {
152
				$item_meta[] = array(
153
					'key'   => $formatted_meta['key'],
154
					'label' => $formatted_meta['label'],
155
					'value' => $formatted_meta['value'],
156
				);
157
			}
158
159
			$line_item = array(
160
				'id'           => $item_id,
161
				'name'         => $item['name'],
162
				'sku'          => $product_sku,
163
				'product_id'   => (int) $product_id,
164
				'variation_id' => (int) $variation_id,
165
				'quantity'     => wc_stock_amount( $item['qty'] ),
166
				'tax_class'    => ! empty( $item['tax_class'] ) ? $item['tax_class'] : '',
167
				'price'        => wc_format_decimal( $refund->get_item_total( $item, false, false ), $dp ),
168
				'subtotal'     => wc_format_decimal( $refund->get_line_subtotal( $item, false, false ), $dp ),
169
				'subtotal_tax' => wc_format_decimal( $item['line_subtotal_tax'], $dp ),
170
				'total'        => wc_format_decimal( $refund->get_line_total( $item, false, false ), $dp ),
171
				'total_tax'    => wc_format_decimal( $item['line_tax'], $dp ),
172
				'taxes'        => array(),
173
				'meta'         => $item_meta,
174
			);
175
176
			$item_line_taxes = maybe_unserialize( $item['line_tax_data'] );
177
			if ( isset( $item_line_taxes['total'] ) ) {
178
				$line_tax = array();
179
180
				foreach ( $item_line_taxes['total'] as $tax_rate_id => $tax ) {
181
					$line_tax[ $tax_rate_id ] = array(
182
						'id'       => $tax_rate_id,
183
						'total'    => $tax,
184
						'subtotal' => '',
185
					);
186
				}
187
188
				foreach ( $item_line_taxes['subtotal'] as $tax_rate_id => $tax ) {
189
					$line_tax[ $tax_rate_id ]['subtotal'] = $tax;
190
				}
191
192
				$line_item['taxes'] = array_values( $line_tax );
193
			}
194
195
			$data['line_items'][] = $line_item;
196
		}
197
198
		$context = ! empty( $request['context'] ) ? $request['context'] : 'view';
199
		$data    = $this->add_additional_fields_to_object( $data, $request );
200
		$data    = $this->filter_response_by_context( $data, $context );
201
202
		// Wrap the data in a response object.
203
		$response = rest_ensure_response( $data );
204
205
		$response->add_links( $this->prepare_links( $refund ) );
206
207
		/**
208
		 * Filter the data for a response.
209
		 *
210
		 * The dynamic portion of the hook name, $this->post_type, refers to post_type of the post being
211
		 * prepared for the response.
212
		 *
213
		 * @param WP_REST_Response   $response   The response object.
214
		 * @param WP_Post            $post       Post object.
215
		 * @param WP_REST_Request    $request    Request object.
216
		 */
217
		return apply_filters( "woocommerce_rest_prepare_{$this->post_type}", $response, $post, $request );
218
	}
219
220
	/**
221
	 * Prepare links for the request.
222
	 *
223
	 * @param WC_Order_Refund $refund Comment object.
224
	 * @return array Links for the given order refund.
225
	 */
226 View Code Duplication
	protected function prepare_links( $refund ) {
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...
227
		$order_id = $refund->post->post_parent;
228
		$base     = str_replace( '(?P<order_id>[\d]+)', $order_id, $this->rest_base );
229
		$links    = array(
230
			'self' => array(
231
				'href' => rest_url( sprintf( '/%s/%s/%d', $this->namespace, $base, $refund->id ) ),
232
			),
233
			'collection' => array(
234
				'href' => rest_url( sprintf( '/%s/%s', $this->namespace, $base ) ),
235
			),
236
			'up' => array(
237
				'href' => rest_url( sprintf( '/%s/orders/%d', $this->namespace, $order_id ) ),
238
			),
239
		);
240
241
		return $links;
242
	}
243
244
	/**
245
	 * Query args.
246
	 *
247
	 * @param array $args
248
	 * @param WP_REST_Request $request
249
	 * @return array
250
	 */
251
	public function query_args( $args, $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...
252
		// Set post_status.
253
		$args['post_status'] = 'any';
254
255
		return $args;
256
	}
257
258
	/**
259
	 * Create a single item.
260
	 *
261
	 * @param WP_REST_Request $request Full details about the request.
262
	 * @return WP_Error|WP_REST_Response
263
	 */
264
	public function create_item( $request ) {
265
		if ( ! empty( $request['id'] ) ) {
266
			return new WP_Error( "woocommerce_rest_{$this->post_type}_exists", sprintf( __( 'Cannot create existing %s.', 'woocommerce' ), $this->post_type ), array( 'status' => 400 ) );
267
		}
268
269
		$order_data = get_post( (int) $request['order_id'] );
270
271
		if ( empty( $order_data ) ) {
272
			return new WP_Error( 'woocommerce_rest_invalid_order', __( 'Order is invalid', 'woocommerce' ), 400 );
273
		}
274
275
		if ( 0 > $request['amount'] ) {
276
			return new WP_Error( 'woocommerce_rest_invalid_order_refund', __( 'Refund amount must be greater than zero.', 'woocommerce' ), 400 );
277
		}
278
279
		$api_refund = is_bool( $request['api_refund'] ) ? $request['api_refund'] : true;
280
281
		$data = array(
282
			'order_id'   => $order_data->ID,
283
			'amount'     => $request['amount'],
284
			'line_items' => $request['line_items'],
285
		);
286
287
		// Create the refund.
288
		$refund = wc_create_refund( $data );
289
290
		if ( ! $refund ) {
291
			return new WP_Error( 'woocommerce_rest_cannot_create_order_refund', __( 'Cannot create order refund, please try again.', 'woocommerce' ), 500 );
292
		}
293
294
		// Refund via API.
295
		if ( $api_refund ) {
296
			if ( WC()->payment_gateways() ) {
297
				$payment_gateways = WC()->payment_gateways->payment_gateways();
298
			}
299
300
			$order = wc_get_order( $order_data );
301
302
			if ( isset( $payment_gateways[ $order->payment_method ] ) && $payment_gateways[ $order->payment_method ]->supports( 'refunds' ) ) {
303
				$result = $payment_gateways[ $order->payment_method ]->process_refund( $order_id, $refund->get_refund_amount(), $refund->get_refund_reason() );
304
305 View Code Duplication
				if ( is_wp_error( $result ) ) {
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...
306
					return $result;
307
				} elseif ( ! $result ) {
308
					return new WP_Error( 'woocommerce_rest_create_order_refund_api_failed', __( 'An error occurred while attempting to create the refund using the payment gateway API.', 'woocommerce' ), 500 );
309
				}
310
			}
311
		}
312
313
		$post = get_post( $refund->id );
314
		$this->update_additional_fields_for_object( $post, $request );
315
316
		/**
317
		 * Fires after a single item is created or updated via the REST API.
318
		 *
319
		 * @param object          $post      Inserted object (not a WP_Post object).
320
		 * @param WP_REST_Request $request   Request object.
321
		 * @param boolean         $creating  True when creating item, false when updating.
322
		 */
323
		do_action( "woocommerce_rest_insert_{$this->post_type}", $post, $request, true );
324
325
		$request->set_param( 'context', 'edit' );
326
		$response = $this->prepare_item_for_response( $post, $request );
327
		$response = rest_ensure_response( $response );
328
		$response->set_status( 201 );
329
		$response->header( 'Location', rest_url( sprintf( '/%s/%s/%d', $this->namespace, $this->rest_base, $post->ID ) ) );
330
331
		return $response;
332
	}
333
334
	/**
335
	 * Get the Order's schema, conforming to JSON Schema.
336
	 *
337
	 * @return array
338
	 */
339
	public function get_item_schema() {
340
		$schema = array(
341
			'$schema'    => 'http://json-schema.org/draft-04/schema#',
342
			'title'      => $this->post_type,
343
			'type'       => 'object',
344
			'properties' => array(
345
				'id' => array(
346
					'description' => __( 'Unique identifier for the resource.', 'woocommerce' ),
347
					'type'        => 'integer',
348
					'context'     => array( 'view', 'edit' ),
349
					'readonly'    => true,
350
				),
351
				'date_created' => array(
352
					'description' => __( "The date the order refund was created, in the site's timezone.", 'woocommerce' ),
353
					'type'        => 'date-time',
354
					'context'     => array( 'view', 'edit' ),
355
					'readonly'    => true,
356
				),
357
				'amount' => array(
358
					'description' => __( 'Refund amount.', 'woocommerce' ),
359
					'type'        => 'string',
360
					'context'     => array( 'view', 'edit' ),
361
				),
362
				'reason' => array(
363
					'description' => __( 'Reason for refund.', 'woocommerce' ),
364
					'type'        => 'string',
365
					'context'     => array( 'view', 'edit' ),
366
				),
367
				'line_items' => array(
368
					'description' => __( 'Line items data.', 'woocommerce' ),
369
					'type'        => 'array',
370
					'context'     => array( 'view', 'edit' ),
371
					'properties'  => array(
372
						'id' => array(
373
							'description' => __( 'Item ID.', 'woocommerce' ),
374
							'type'        => 'integer',
375
							'context'     => array( 'view', 'edit' ),
376
							'readonly'    => true,
377
						),
378
						'name' => array(
379
							'description' => __( 'Product name.', 'woocommerce' ),
380
							'type'        => 'integer',
381
							'context'     => array( 'view', 'edit' ),
382
							'readonly'    => true,
383
						),
384
						'sku' => array(
385
							'description' => __( 'Product SKU.', 'woocommerce' ),
386
							'type'        => 'string',
387
							'context'     => array( 'view', 'edit' ),
388
							'readonly'    => true,
389
						),
390
						'product_id' => array(
391
							'description' => __( 'Product ID.', 'woocommerce' ),
392
							'type'        => 'integer',
393
							'context'     => array( 'view', 'edit' ),
394
						),
395
						'variation_id' => array(
396
							'description' => __( 'Variation ID, if applicable.', 'woocommerce' ),
397
							'type'        => 'integer',
398
							'context'     => array( 'view', 'edit' ),
399
						),
400
						'quantity' => array(
401
							'description' => __( 'Quantity ordered.', 'woocommerce' ),
402
							'type'        => 'integer',
403
							'context'     => array( 'view', 'edit' ),
404
						),
405
						'tax_class' => array(
406
							'description' => __( 'Tax class of product.', 'woocommerce' ),
407
							'type'        => 'string',
408
							'context'     => array( 'view', 'edit' ),
409
							'readonly'    => true,
410
						),
411
						'price' => array(
412
							'description' => __( 'Product price.', 'woocommerce' ),
413
							'type'        => 'string',
414
							'context'     => array( 'view', 'edit' ),
415
							'readonly'    => true,
416
						),
417
						'subtotal' => array(
418
							'description' => __( 'Line subtotal (before discounts).', 'woocommerce' ),
419
							'type'        => 'string',
420
							'context'     => array( 'view', 'edit' ),
421
						),
422
						'subtotal_tax' => array(
423
							'description' => __( 'Line subtotal tax (before discounts).', 'woocommerce' ),
424
							'type'        => 'string',
425
							'context'     => array( 'view', 'edit' ),
426
						),
427
						'total' => array(
428
							'description' => __( 'Line total (after discounts).', 'woocommerce' ),
429
							'type'        => 'string',
430
							'context'     => array( 'view', 'edit' ),
431
						),
432
						'total_tax' => array(
433
							'description' => __( 'Line total tax (after discounts).', 'woocommerce' ),
434
							'type'        => 'string',
435
							'context'     => array( 'view', 'edit' ),
436
						),
437
						'taxes' => array(
438
							'description' => __( 'Line taxes.', 'woocommerce' ),
439
							'type'        => 'array',
440
							'context'     => array( 'view', 'edit' ),
441
							'readonly'    => true,
442
							'properties'  => array(
443
								'id' => array(
444
									'description' => __( 'Tax rate ID.', 'woocommerce' ),
445
									'type'        => 'integer',
446
									'context'     => array( 'view', 'edit' ),
447
									'readonly'    => true,
448
								),
449
								'total' => array(
450
									'description' => __( 'Tax total.', 'woocommerce' ),
451
									'type'        => 'string',
452
									'context'     => array( 'view', 'edit' ),
453
									'readonly'    => true,
454
								),
455
								'subtotal' => array(
456
									'description' => __( 'Tax subtotal.', 'woocommerce' ),
457
									'type'        => 'string',
458
									'context'     => array( 'view', 'edit' ),
459
									'readonly'    => true,
460
								),
461
							),
462
						),
463
						'meta' => array(
464
							'description' => __( 'Line item meta data.', 'woocommerce' ),
465
							'type'        => 'array',
466
							'context'     => array( 'view', 'edit' ),
467
							'readonly'    => true,
468
							'properties'  => array(
469
								'key' => array(
470
									'description' => __( 'Meta key.', 'woocommerce' ),
471
									'type'        => 'string',
472
									'context'     => array( 'view', 'edit' ),
473
									'readonly'    => true,
474
								),
475
								'label' => array(
476
									'description' => __( 'Meta label.', 'woocommerce' ),
477
									'type'        => 'string',
478
									'context'     => array( 'view', 'edit' ),
479
									'readonly'    => true,
480
								),
481
								'value' => array(
482
									'description' => __( 'Meta value.', 'woocommerce' ),
483
									'type'        => 'string',
484
									'context'     => array( 'view', 'edit' ),
485
									'readonly'    => true,
486
								),
487
							),
488
						),
489
					),
490
				),
491
			),
492
		);
493
494
		return $this->add_additional_fields_schema( $schema );
495
	}
496
497
	/**
498
	 * Get the query params for collections.
499
	 *
500
	 * @return array
501
	 */
502 View Code Duplication
	public function get_collection_params() {
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...
503
		$params = parent::get_collection_params();
504
505
		$params['dp'] = array(
506
			'default'           => 2,
507
			'description'       => __( 'Number of decimal points to use in each resource.', 'woocommerce' ),
508
			'type'              => 'integer',
509
			'sanitize_callback' => 'absint',
510
			'validate_callback' => 'rest_validate_request_arg',
511
		);
512
513
		return $params;
514
	}
515
}
516