Completed
Pull Request — trunk (#541)
by Justin
07:44
created

CMB2_REST_Controller   A

Complexity

Total Complexity 28

Size/Duplication

Total Lines 318
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 3
Metric Value
wmc 28
lcom 1
cbo 3
dl 0
loc 318
rs 10

10 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 3 1
B get_rest_box() 0 46 2
B get_rest_field() 0 43 3
D prepare_field_data() 0 47 13
A get_item_permissions_check() 0 13 1
A prepare_item() 0 3 1
A get_cb_results() 0 8 1
A initiate_request() 0 11 3
A prepare_item_for_response() 0 16 2
B get_item_schema() 0 26 1
1
<?php
2
/**
3
 * Creates CMB2 objects/fields endpoint for WordPres REST API.
4
 * Allows access to fields registered to a specific post type and more.
5
 *
6
 * @todo  Add better documentation.
7
 * @todo  Research proper schema.
8
 *
9
 * @since 2.2.0
10
 *
11
 * @category  WordPress_Plugin
12
 * @package   CMB2
13
 * @author    WebDevStudios
14
 * @license   GPL-2.0+
15
 * @link      http://webdevstudios.com
16
 */
17
abstract class CMB2_REST_Controller extends WP_REST_Controller {
0 ignored issues
show
Coding Style Compatibility introduced by
PSR1 recommends that each class must be in a namespace of at least one level to avoid collisions.

You can fix this by adding a namespace to your class:

namespace YourVendor;

class YourClass { }

When choosing a vendor namespace, try to pick something that is not too generic to avoid conflicts with other libraries.

Loading history...
18
19
	/**
20
	 * The current request object
21
	 * @var WP_REST_Request $request
22
	 * @since 2.2.0
23
	 */
24
	public $request;
25
26
	/**
27
	 * The current server object
28
	 * @var WP_REST_Server $server
29
	 * @since 2.2.0
30
	 */
31
	public $server;
32
33
	/**
34
	 * Box object id
35
	 * @var   mixed
36
	 * @since 2.2.0
37
	 */
38
	public $object_id = null;
39
40
	/**
41
	 * Box object type
42
	 * @var   string
43
	 * @since 2.2.0
44
	 */
45
	public $object_type = '';
46
47
	/**
48
	 * Constructor
49
	 * @since 2.2.0
50
	 */
51
	public function __construct( WP_REST_Server $wp_rest_server ) {
52
		$this->server = $wp_rest_server;
53
	}
54
55
	/**
56
	 * Get a CMB2 box prepared for REST
57
	 *
58
	 * @since 2.2.0
59
	 *
60
	 * @param CMB2 $cmb
61
	 * @return array
62
	 */
63
	public function get_rest_box( $cmb ) {
0 ignored issues
show
Coding Style introduced by
get_rest_box uses the super-global variable $_REQUEST which is generally not recommended.

Instead of super-globals, we recommend to explicitly inject the dependencies of your class. This makes your code less dependent on global state and it becomes generally more testable:

// Bad
class Router
{
    public function generate($path)
    {
        return $_SERVER['HOST'].$path;
    }
}

// Better
class Router
{
    private $host;

    public function __construct($host)
    {
        $this->host = $host;
    }

    public function generate($path)
    {
        return $this->host.$path;
    }
}

class Controller
{
    public function myAction(Request $request)
    {
        // Instead of
        $page = isset($_GET['page']) ? intval($_GET['page']) : 1;

        // Better (assuming you use the Symfony2 request)
        $page = $request->query->get('page', 1);
    }
}
Loading history...
64
		$cmb->object_type( $this->object_id );
65
		$cmb->object_id( $this->object_type );
66
67
		$boxes_data = $cmb->meta_box;
68
69
		if ( isset( $_REQUEST['rendered'] ) ) {
70
			$boxes_data['form_open'] = $this->get_cb_results( array( $cmb, 'render_form_open' ) );
71
			$boxes_data['form_close'] = $this->get_cb_results( array( $cmb, 'render_form_close' ) );
72
73
			global $wp_scripts, $wp_styles;
0 ignored issues
show
Compatibility Best Practice introduced by
Use of global functionality is not recommended; it makes your code harder to test, and less reusable.

Instead of relying on global state, we recommend one of these alternatives:

1. Pass all data via parameters

function myFunction($a, $b) {
    // Do something
}

2. Create a class that maintains your state

class MyClass {
    private $a;
    private $b;

    public function __construct($a, $b) {
        $this->a = $a;
        $this->b = $b;
    }

    public function myFunction() {
        // Do something
    }
}
Loading history...
74
			$before_css = $wp_styles->queue;
75
			$before_js = $wp_scripts->queue;
76
77
			CMB2_JS::enqueue();
78
79
			$boxes_data['js_dependencies'] = array_values( array_diff( $wp_scripts->queue, $before_js ) );
80
			$boxes_data['css_dependencies'] = array_values( array_diff( $wp_styles->queue, $before_css ) );
81
		}
82
83
		// TODO: look into 'embed' parameter.
84
		// http://demo.wp-api.org/wp-json/wp/v2/posts?_embed
85
		unset( $boxes_data['fields'] );
86
		// Handle callable properties.
87
		unset( $boxes_data['show_on_cb'] );
88
89
		$base = CMB2_REST::BASE . '/boxes/' . $cmb->cmb_id;
90
		$boxbase = $base . '/' . $cmb->cmb_id;
91
92
		$response = new WP_REST_Response( $boxes_data );
93
		$response->add_links( array(
94
			'self' => array(
95
				'href' => rest_url( trailingslashit( $boxbase ) ),
96
			),
97
			'collection' => array(
98
				'href' => rest_url( trailingslashit( $base ) ),
99
			),
100
			'fields' => array(
101
				'href' => rest_url( trailingslashit( $boxbase ) . 'fields/' ),
102
			),
103
		) );
104
105
		$boxes_data['_links'] = $response->get_links();
106
107
		return $boxes_data;
108
	}
109
110
	/**
111
	 * Get a specific field
112
	 *
113
	 * @since 2.2.0
114
	 *
115
	 * @param CMB2 $cmb
116
	 * @return array|WP_Error
117
	 */
118
	public function get_rest_field( $cmb, $field_id ) {
119
120
		// TODO: more robust show_in_rest checking. use rest_read/rest_write properties.
121
		// TODO: more robust show_in_rest checking. use rest_read/rest_write properties.
122
		// TODO: more robust show_in_rest checking. use rest_read/rest_write properties.
123
124
		if ( ! $cmb->prop( 'show_in_rest' ) ) {
125
			return new WP_Error( 'cmb2_rest_error', __( "You don't have permission to view this field.", 'cmb2' ) );
126
		}
127
128
		$field = $cmb->get_field( $field_id );
129
130
		if ( ! $field ) {
131
			return new WP_Error( 'cmb2_rest_error', __( 'No field found by that id.', 'cmb2' ) );
132
		}
133
134
		// TODO: check for show_in_rest property.
135
		// $can_read = $this->can_read
0 ignored issues
show
Unused Code Comprehensibility introduced by
38% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
136
		// 	? 'write_only' !== $show_in_rest
0 ignored issues
show
Unused Code Comprehensibility introduced by
45% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
137
		// 	: in_array( $show_in_rest, array( 'read_and_write', 'read_only' ), true );
0 ignored issues
show
Unused Code Comprehensibility introduced by
59% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
138
139
140
		$field_data = $this->prepare_field_data( $field );
141
142
		$base = CMB2_REST::BASE . '/boxes/' . $cmb->cmb_id;
143
144
		$response = new WP_REST_Response( $field_data );
145
		$response->add_links( array(
146
			'self' => array(
147
				'href' => rest_url( trailingslashit( $base ) . 'fields/' . $field->_id() ),
148
			),
149
			'collection' => array(
150
				'href' => rest_url( trailingslashit( $base ) . 'fields/' ),
151
			),
152
			'box' => array(
153
				'href' => rest_url( trailingslashit( $base ) ),
154
			),
155
		) );
156
157
		$field_data['_links'] = $response->get_links();
158
159
		return $field_data;
160
	}
161
162
	public function prepare_field_data( CMB2_Field $field ) {
0 ignored issues
show
Coding Style introduced by
prepare_field_data uses the super-global variable $_REQUEST which is generally not recommended.

Instead of super-globals, we recommend to explicitly inject the dependencies of your class. This makes your code less dependent on global state and it becomes generally more testable:

// Bad
class Router
{
    public function generate($path)
    {
        return $_SERVER['HOST'].$path;
    }
}

// Better
class Router
{
    private $host;

    public function __construct($host)
    {
        $this->host = $host;
    }

    public function generate($path)
    {
        return $this->host.$path;
    }
}

class Controller
{
    public function myAction(Request $request)
    {
        // Instead of
        $page = isset($_GET['page']) ? intval($_GET['page']) : 1;

        // Better (assuming you use the Symfony2 request)
        $page = $request->query->get('page', 1);
    }
}
Loading history...
163
		$field_data = array();
164
		$params_to_ignore = array( 'show_on_cb', 'show_in_rest', 'options' );
165
		$params_to_rename = array(
166
			'label_cb' => 'label',
167
			'options_cb' => 'options',
168
		);
169
170
		// TODO: Use request get object
171
		// Run this first so the js_dependencies arg is populated.
172
		$rendered = isset( $_REQUEST['rendered'] ) && ( $cb = $field->maybe_callback( 'render_row_cb' ) )
173
			// Ok, callback is good, let's run it.
174
			? $this->get_cb_results( $cb, $field->args(), $field )
0 ignored issues
show
Bug introduced by
The variable $cb does not seem to be defined for all execution paths leading up to this point.

If you define a variable conditionally, it can happen that it is not defined for all execution paths.

Let’s take a look at an example:

function myFunction($a) {
    switch ($a) {
        case 'foo':
            $x = 1;
            break;

        case 'bar':
            $x = 2;
            break;
    }

    // $x is potentially undefined here.
    echo $x;
}

In the above example, the variable $x is defined if you pass “foo” or “bar” as argument for $a. However, since the switch statement has no default case statement, if you pass any other value, the variable $x would be undefined.

Available Fixes

  1. Check for existence of the variable explicitly:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        if (isset($x)) { // Make sure it's always set.
            echo $x;
        }
    }
    
  2. Define a default value for the variable:

    function myFunction($a) {
        $x = ''; // Set a default which gets overridden for certain paths.
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        echo $x;
    }
    
  3. Add a value for the missing path:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
    
            // We add support for the missing case.
            default:
                $x = '';
                break;
        }
    
        echo $x;
    }
    
Loading history...
175
			: false;
176
177
		foreach ( $field->args() as $key => $value ) {
178
			if ( in_array( $key, $params_to_ignore, true ) ) {
179
				continue;
180
			}
181
182
			if ( 'render_row_cb' === $key ) {
183
				continue;
184
			}
185
186
			if ( 'options_cb' === $key ) {
187
				$value = $field->options();
188
			} elseif ( in_array( $key, CMB2_Field::$callable_fields ) ) {
189
				$value = $field->get_param_callback_result( $key );
190
			}
191
192
			$key = isset( $params_to_rename[ $key ] ) ? $params_to_rename[ $key ] : $key;
193
194
			if ( empty( $value ) || is_scalar( $value ) || is_array( $value ) ) {
195
				$field_data[ $key ] = $value;
196
			} else {
197
				$field_data[ $key ] = __( 'Value Error', 'cmb2' );
198
			}
199
		}
200
201
		if ( isset( $_REQUEST['rendered'] ) ) {
202
			$field_data['rendered'] = $rendered;
203
		}
204
205
		$field_data['value'] = $field->get_data();
206
207
		return $field_data;
208
	}
209
210
	/**
211
	 * Check if a given request has access to a field or box.
212
	 * By default, no special permissions needed, but filtering return value.
213
	 *
214
	 * @since 2.2.0
215
	 *
216
	 * @param  WP_REST_Request $request Full details about the request.
217
	 * @return bool
218
	 */
219
	public function get_item_permissions_check( $request ) {
220
		$this->initiate_request( $request );
221
222
		/**
223
		 * By default, no special permissions needed.
224
		 *
225
		 * @since 2.2.0
226
		 *
227
		 * @param object $request        The WP_REST_Request object
228
		 * @param object $cmb2_endpoints This endpoints object
229
		 */
230
		return apply_filters( 'cmb2_request_permissions_check', true, $this->request );
231
	}
232
233
	/**
234
	 * Prepare a CMB2 object for serialization
235
	 *
236
	 * @since 2.2.0
237
	 *
238
	 * @param  mixed $data
0 ignored issues
show
Bug introduced by
There is no parameter named $data. Was it maybe removed?

This check looks for PHPDoc comments describing methods or function parameters that do not exist on the corresponding method or function.

Consider the following example. The parameter $italy is not defined by the method finale(...).

/**
 * @param array $germany
 * @param array $island
 * @param array $italy
 */
function finale($germany, $island) {
    return "2:1";
}

The most likely cause is that the parameter was removed, but the annotation was not.

Loading history...
239
	 * @return array $data
240
	 */
241
	public function prepare_item( $post ) {
242
		return $this->prepare_item_for_response( $post, $this->request );
243
	}
244
245
	/**
246
	 * Output buffers a callback and returns the results.
247
	 *
248
	 * @since  2.2.0
249
	 *
250
	 * @param  mixed $cb Callable function/method.
251
	 * @return mixed     Results of output buffer after calling function/method.
252
	 */
253
	public function get_cb_results( $cb ) {
254
		$args = func_get_args();
255
		array_shift( $args ); // ignore $cb
256
		ob_start();
257
		call_user_func_array( $cb, $args );
258
259
		return ob_get_clean();
260
	}
261
262
	public function initiate_request( $request ) {
0 ignored issues
show
Coding Style introduced by
initiate_request uses the super-global variable $_REQUEST which is generally not recommended.

Instead of super-globals, we recommend to explicitly inject the dependencies of your class. This makes your code less dependent on global state and it becomes generally more testable:

// Bad
class Router
{
    public function generate($path)
    {
        return $_SERVER['HOST'].$path;
    }
}

// Better
class Router
{
    private $host;

    public function __construct($host)
    {
        $this->host = $host;
    }

    public function generate($path)
    {
        return $this->host.$path;
    }
}

class Controller
{
    public function myAction(Request $request)
    {
        // Instead of
        $page = isset($_GET['page']) ? intval($_GET['page']) : 1;

        // Better (assuming you use the Symfony2 request)
        $page = $request->query->get('page', 1);
    }
}
Loading history...
263
		$this->request = $request;
264
265
		if ( isset( $_REQUEST['object_id'] ) ) {
266
			$this->object_id = absint( $_REQUEST['object_id'] );
267
		}
268
269
		if ( isset( $_REQUEST['object_type'] ) ) {
270
			$this->object_type = absint( $_REQUEST['object_type'] );
271
		}
272
	}
273
274
	/**
275
	 * Prepare a CMB2 object for serialization
276
	 *
277
	 * @since 2.2.0
278
	 *
279
	 * @param  mixed           $data
280
	 * @param  WP_REST_Request $request Request object
281
	 * @return array $data
282
	 */
283
	public function prepare_item_for_response( $data, $request ) {
284
285
		$context = ! empty( $this->request['context'] ) ? $this->request['context'] : 'view';
286
		$data = $this->filter_response_by_context( $data, $context );
287
288
		/**
289
		 * Filter the prepared CMB2 item response.
290
		 *
291
		 * @since 2.2.0
292
		 *
293
		 * @param mixed  $data           Prepared data
294
		 * @param object $request        The WP_REST_Request object
295
		 * @param object $cmb2_endpoints This endpoints object
296
		 */
297
		return apply_filters( 'cmb2_rest_prepare', $data, $this->request, $this );
298
	}
299
300
	/**
301
	 * Get CMB2 fields schema, conforming to JSON Schema
302
	 *
303
	 * @since 2.2.0
304
	 *
305
	 * @return array
306
	 */
307
	public function get_item_schema() {
308
		$schema = array(
309
			'$schema'              => 'http://json-schema.org/draft-04/schema#',
310
			'title'                => 'CMB2',
311
			'type'                 => 'object',
312
			'properties'           => array(
313
				'description' => array(
314
					'description'  => 'A human-readable description of the object.',
315
					'type'         => 'string',
316
					'context'      => array( 'view' ),
317
					),
318
					'name'             => array(
319
						'description'  => 'The id for the object.',
320
						'type'         => 'integer',
321
						'context'      => array( 'view' ),
322
					),
323
				'name' => array(
324
					'description'  => 'The title for the object.',
325
					'type'         => 'string',
326
					'context'      => array( 'view' ),
327
				),
328
			),
329
		);
330
331
		return $this->add_additional_fields_schema( $schema );
332
	}
333
334
}
335