WC_REST_Controller::batch_items()   C
last analyzed

Complexity

Conditions 13
Paths 9

Size

Total Lines 79
Code Lines 47

Duplication

Lines 32
Ratio 40.51 %

Importance

Changes 0
Metric Value
cc 13
eloc 47
c 0
b 0
f 0
nc 9
nop 1
dl 32
loc 79
rs 5.1136

How to fix   Long Method    Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
3
if ( ! defined( 'ABSPATH' ) ) {
4
	exit;
5
}
6
7
/**
8
 * Abstract Rest Controler Class
9
 *
10
 * @author   WooThemes
11
 * @category API
12
 * @package  WooCommerce/Abstracts
13
 * @extends  WP_REST_Controller
14
 * @version  2.6.0
15
 */
16
abstract class WC_REST_Controller extends WP_REST_Controller {
17
18
	/**
19
	 * Endpoint namespace.
20
	 *
21
	 * @var string
22
	 */
23
	protected $namespace = 'wc/v1';
24
25
	/**
26
	 * Route base.
27
	 *
28
	 * @var string
29
	 */
30
	protected $rest_base = '';
31
32
	/**
33
	 * Add the schema from additional fields to an schema array.
34
	 *
35
	 * The type of object is inferred from the passed schema.
36
	 *
37
	 * @param array $schema Schema array.
38
	 */
39
	protected function add_additional_fields_schema( $schema ) {
40
		if ( empty( $schema['title'] ) ) {
41
			return $schema;
42
		}
43
44
		/**
45
		 * Can't use $this->get_object_type otherwise we cause an inf loop.
46
		 */
47
		$object_type = $schema['title'];
48
49
		$additional_fields = $this->get_additional_fields( $object_type );
50
51 View Code Duplication
		foreach ( $additional_fields as $field_name => $field_options ) {
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...
52
			if ( ! $field_options['schema'] ) {
53
				continue;
54
			}
55
56
			$schema['properties'][ $field_name ] = $field_options['schema'];
57
		}
58
59
		$schema['properties'] = apply_filters( 'woocommerce_rest_' . $object_type . '_schema', $schema['properties'] );
60
61
		return $schema;
62
	}
63
64
	/**
65
	 * Get normalized rest base.
66
	 *
67
	 * @return string
68
	 */
69
	protected function get_normalized_rest_base() {
70
		return preg_replace( '/\(.*\)\//i', '', $this->rest_base );
71
	}
72
73
	/**
74
	 * Check batch limit.
75
	 *
76
	 * @param array $items Request items.
77
	 * @return bool|WP_Error
78
	 */
79
	protected function check_batch_limit( $items ) {
80
		$limit = apply_filters( 'woocommerce_rest_batch_items_limit', 100, $this->get_normalized_rest_base() );
81
		$total = 0;
82
83
		if ( ! empty( $items['create'] ) ) {
84
			$total += count( $items['create'] );
85
		}
86
87
		if ( ! empty( $items['update'] ) ) {
88
			$total += count( $items['update'] );
89
		}
90
91
		if ( ! empty( $items['delete'] ) ) {
92
			$total += count( $items['delete'] );
93
		}
94
95
		if ( $total > $limit ) {
96
			return new WP_Error( 'woocommerce_rest_request_entity_too_large', sprintf( __( 'Unable to accept more than %s items for this request.', 'woocommerce' ), $limit ), array( 'status' => 413 ) );
97
		}
98
99
		return true;
100
	}
101
102
	/**
103
	 * Bulk create, update and delete items.
104
	 *
105
	 * @param WP_REST_Request $request Full details about the request.
106
	 * @return array Of WP_Error or WP_REST_Response.
107
	 */
108
	public function batch_items( $request ) {
109
		/** @var WP_REST_Server $wp_rest_server */
110
		global $wp_rest_server;
111
112
		// Get the request params.
113
		$items    = array_filter( $request->get_params() );
114
		$response = array();
115
116
		// Check batch limit.
117
		$limit = $this->check_batch_limit( $items );
118
		if ( is_wp_error( $limit ) ) {
119
			return $limit;
120
		}
121
122
		if ( ! empty( $items['create'] ) ) {
123
			foreach ( $items['create'] as $item ) {
124
				$_item = new WP_REST_Request( 'POST' );
125
126
				// Default parameters.
127
				$defaults = array();
128
				$schema   = $this->get_public_item_schema();
129
				foreach ( $schema['properties'] as $arg => $options ) {
130
					if ( isset( $options['default'] ) ) {
131
						$defaults[ $arg ] = $options['default'];
132
					}
133
				}
134
				$_item->set_default_params( $defaults );
135
136
				// Set request parameters.
137
				$_item->set_body_params( $item );
138
				$_response = $this->create_item( $_item );
139
140
				if ( is_wp_error( $_response ) ) {
141
					$response['create'][] = array(
142
						'id'    => 0,
143
						'error' => array( 'code' => $_response->get_error_code(), 'message' => $_response->get_error_message(), 'data' => $_response->get_error_data() ),
144
					);
145
				} else {
146
					$response['create'][] = $wp_rest_server->response_to_data( $_response, '' );
147
				}
148
			}
149
		}
150
151 View Code Duplication
		if ( ! empty( $items['update'] ) ) {
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...
152
			foreach ( $items['update'] as $item ) {
153
				$_item = new WP_REST_Request( 'PUT' );
154
				$_item->set_body_params( $item );
155
				$_response = $this->update_item( $_item );
156
157
				if ( is_wp_error( $_response ) ) {
158
					$response['update'][] = array(
159
						'id'    => $item['id'],
160
						'error' => array( 'code' => $_response->get_error_code(), 'message' => $_response->get_error_message(), 'data' => $_response->get_error_data() ),
161
					);
162
				} else {
163
					$response['update'][] = $wp_rest_server->response_to_data( $_response, '' );
164
				}
165
			}
166
		}
167
168 View Code Duplication
		if ( ! empty( $items['delete'] ) ) {
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...
169
			foreach ( $items['delete'] as $id ) {
170
				$_item = new WP_REST_Request( 'DELETE' );
171
				$_item->set_query_params( array( 'id' => $id, 'force' => true ) );
172
				$_response = $this->delete_item( $_item );
173
174
				if ( is_wp_error( $_response ) ) {
175
					$response['delete'][] = array(
176
						'id'    => $id,
177
						'error' => array( 'code' => $_response->get_error_code(), 'message' => $_response->get_error_message(), 'data' => $_response->get_error_data() ),
178
					);
179
				} else {
180
					$response['delete'][] = $wp_rest_server->response_to_data( $_response, '' );
181
				}
182
			}
183
		}
184
185
		return $response;
186
	}
187
188
	/**
189
	 * Get the batch schema, conforming to JSON Schema.
190
	 *
191
	 * @return array
192
	 */
193
	public function get_public_batch_schema() {
194
		$schema = array(
195
			'$schema'    => 'http://json-schema.org/draft-04/schema#',
196
			'title'      => 'batch',
197
			'type'       => 'object',
198
			'properties' => array(
199
				'create' => array(
200
					'description' => __( 'List of created resources.', 'woocommerce' ),
201
					'type'        => 'array',
202
					'context'     => array( 'view', 'edit' ),
203
				),
204
				'update' => array(
205
					'description' => __( 'List of updated resources.', 'woocommerce' ),
206
					'type'        => 'array',
207
					'context'     => array( 'view', 'edit' ),
208
				),
209
				'delete' => array(
210
					'description' => __( 'List of delete resources.', 'woocommerce' ),
211
					'type'        => 'array',
212
					'context'     => array( 'view', 'edit' ),
213
				),
214
			),
215
		);
216
217
		return $schema;
218
	}
219
}
220