Completed
Pull Request — trunk (#541)
by Justin
06:33
created

CMB2_REST_Controller::get_query_string()   B

Complexity

Conditions 5
Paths 6

Size

Total Lines 22
Code Lines 13

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 5
eloc 13
c 0
b 0
f 0
nc 6
nop 0
dl 0
loc 22
rs 8.6737
1
<?php
0 ignored issues
show
Coding Style Compatibility introduced by
For compatibility and reusability of your code, PSR1 recommends that a file should introduce either new symbols (like classes, functions, etc.) or have side-effects (like outputting something, or including other files), but not both at the same time. The first symbol is defined on line 22 and the first side effect is on line 4.

The PSR-1: Basic Coding Standard recommends that a file should either introduce new symbols, that is classes, functions, constants or similar, or have side effects. Side effects are anything that executes logic, like for example printing output, changing ini settings or writing to a file.

The idea behind this recommendation is that merely auto-loading a class should not change the state of an application. It also promotes a cleaner style of programming and makes your code less prone to errors, because the logic is not spread out all over the place.

To learn more about the PSR-1, please see the PHP-FIG site on the PSR-1.

Loading history...
2
if ( ! class_exists( 'WP_REST_Controller' ) ) {
3
	// Shim the WP_REST_Controller class if wp-api plugin not installed, & not in core.
4
	require_once cmb2_dir( 'includes/shim/WP_REST_Controller.php' );
5
}
6
7
/**
8
 * Creates CMB2 objects/fields endpoint for WordPres REST API.
9
 * Allows access to fields registered to a specific post type and more.
10
 *
11
 * @todo  Add better documentation.
12
 * @todo  Research proper schema.
13
 *
14
 * @since 2.2.4
15
 *
16
 * @category  WordPress_Plugin
17
 * @package   CMB2
18
 * @author    WebDevStudios
19
 * @license   GPL-2.0+
20
 * @link      http://webdevstudios.com
21
 */
22
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...
23
24
	/**
25
	 * The namespace of this controller's route.
26
	 *
27
	 * @var string
28
	 */
29
	protected $namespace = CMB2_REST::NAME_SPACE;
30
31
	/**
32
	 * The base of this controller's route.
33
	 *
34
	 * @var string
35
	 */
36
	protected $rest_base;
37
38
	/**
39
	 * The current request object
40
	 * @var WP_REST_Request $request
41
	 * @since 2.2.4
42
	 */
43
	public $request;
44
45
	/**
46
	 * The current server object
47
	 * @var WP_REST_Server $server
48
	 * @since 2.2.4
49
	 */
50
	public $server;
51
52
	/**
53
	 * Box object id
54
	 * @var   mixed
55
	 * @since 2.2.4
56
	 */
57
	public $object_id = null;
58
59
	/**
60
	 * Box object type
61
	 * @var   string
62
	 * @since 2.2.4
63
	 */
64
	public $object_type = '';
65
66
	/**
67
	 * CMB2 Instance
68
	 *
69
	 * @var CMB2_REST
70
	 */
71
	protected $rest_box;
72
73
	/**
74
	 * The initial route
75
	 * @var   string
76
	 * @since 2.2.4
77
	 */
78
	protected static $route = '';
79
80
	/**
81
	 * Defines which endpoint the initial request is.
82
	 * @var string $request_type
83
	 * @since 2.2.4
84
	 */
85
	protected static $request_type = '';
86
87
	/**
88
	 * Constructor
89
	 * @since 2.2.4
90
	 */
91
	public function __construct( WP_REST_Server $wp_rest_server ) {
92
		$this->server = $wp_rest_server;
93
	}
94
95
	/**
96
	 * Check if a given request has access to get items.
97
	 *
98
	 * @since 2.2.4
99
	 *
100
	 * @param  WP_REST_Request $request Full data about the request.
101
	 * @return WP_Error|boolean
102
	 */
103
	public function get_items_permissions_check( $request ) {
104
		$this->initiate_request( $request, __FUNCTION__ );
105
		$can_access = true;
106
107
		$this->maybe_hook_callback( 'get_items_permissions_check_cb' );
108
109
		/**
110
		 * By default, no special permissions needed.
111
		 *
112
		 * @since 2.2.4
113
		 *
114
		 * @param bool   $can_access Whether this CMB2 endpoint can be accessed.
115
		 * @param object $request    The WP_REST_Request object
116
		 */
117
		return apply_filters( 'cmb2_api_get_items_permissions_check', $can_access, $this );
118
	}
119
120
	/**
121
	 * Check if a given request has access to a field or box.
122
	 * By default, no special permissions needed, but filtering return value.
123
	 *
124
	 * @since 2.2.4
125
	 *
126
	 * @param  WP_REST_Request $request Full details about the request.
127
	 * @return WP_Error|boolean
128
	 */
129
	public function get_item_permissions_check( $request ) {
130
		$this->initiate_request( $request, __FUNCTION__ );
131
		$can_access = true;
132
133
		$this->maybe_hook_callback( 'get_item_permissions_check_cb' );
134
135
		/**
136
		 * By default, no special permissions needed.
137
		 *
138
		 * @since 2.2.4
139
		 *
140
		 * @param bool   $can_access Whether this CMB2 endpoint can be accessed.
141
		 * @param object $request    The WP_REST_Request object
142
		 */
143
		return apply_filters( 'cmb2_api_get_item_permissions_check', $can_access, $this );
144
	}
145
146
	/**
147
	 * Check if a given request has access to update a field value.
148
	 * By default, requires 'edit_others_posts' capability, but filtering return value.
149
	 *
150
	 * @since 2.2.4
151
	 *
152
	 * @param  WP_REST_Request $request Full details about the request.
153
	 * @return WP_Error|boolean
154
	 */
155
	public function update_field_value_permissions_check( $request ) {
156
		$this->initiate_request( $request, __FUNCTION__ );
157
		$can_update = current_user_can( 'edit_others_posts' );
158
159
		$this->maybe_hook_callback( 'update_field_value_permissions_check_cb' );
160
161
		/**
162
		 * By default, 'edit_others_posts' is required capability.
163
		 *
164
		 * @since 2.2.4
165
		 *
166
		 * @param bool   $can_update Whether this CMB2 endpoint can be accessed.
167
		 * @param object $request    The WP_REST_Request object
168
		 */
169
		return apply_filters( 'cmb2_api_update_field_value_permissions_check', $can_update, $this );
170
	}
171
172
	/**
173
	 * Check if a given request has access to delete a field value.
174
	 * By default, requires 'delete_others_posts' capability, but filtering return value.
175
	 *
176
	 * @since 2.2.4
177
	 *
178
	 * @param  WP_REST_Request $request Full details about the request.
179
	 * @return WP_Error|boolean
180
	 */
181
	public function delete_field_value_permissions_check( $request ) {
182
		$this->initiate_request( $request, __FUNCTION__ );
183
		$can_delete = current_user_can( 'delete_others_posts' );
184
185
		$this->maybe_hook_callback( 'delete_field_value_permissions_check_cb' );
186
187
		/**
188
		 * By default, 'delete_others_posts' is required capability.
189
		 *
190
		 * @since 2.2.4
191
		 *
192
		 * @param bool   $can_delete Whether this CMB2 endpoint can be accessed.
193
		 * @param object $request    The WP_REST_Request object
194
		 */
195
		return apply_filters( 'cmb2_api_delete_field_value_permissions_check', $can_delete, $this );
196
	}
197
198
	/**
199
	 * Check if a CMB object callback property exists, and if it does,
200
	 * hook it to the permissions filter.
201
	 *
202
	 * @since  2.2.4
203
	 *
204
	 * @param  string  $to_check The callback property to check.
205
	 *
206
	 * @return void
207
	 */
208
	public function maybe_hook_callback( $to_check ) {
209
		if ( ! $this->request->get_param( 'cmb_id' ) ) {
210
			return;
211
		}
212
213
		$rest_box = CMB2_REST::get_rest_box( $this->request->get_param( 'cmb_id' ) );
214
215
		if ( $rest_box && $rest_box->cmb->prop( "{$to_check}" ) ) {
216
			$filter = 'cmb2_api_' . ( substr( $to_check, 0, strlen( $to_check ) - 3 ) );
217
			add_filter( $filter, $rest_box->cmb->prop( "{$to_check}" ), 10, 2 );
218
		}
219
	}
220
221
	/**
222
	 * Prepare a CMB2 object for serialization
223
	 *
224
	 * @since 2.2.4
225
	 *
226
	 * @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...
227
	 * @return array $data
228
	 */
229
	public function prepare_item( $post ) {
230
		return $this->prepare_item_for_response( $post, $this->request );
231
	}
232
233
	/**
234
	 * Output buffers a callback and returns the results.
235
	 *
236
	 * @since  2.2.4
237
	 *
238
	 * @param  mixed $cb Callable function/method.
239
	 * @return mixed     Results of output buffer after calling function/method.
240
	 */
241
	public function get_cb_results( $cb ) {
242
		$args = func_get_args();
243
		array_shift( $args ); // ignore $cb
244
		ob_start();
245
		call_user_func_array( $cb, $args );
246
247
		return ob_get_clean();
248
	}
249
250
	/**
251
	 * Prepare the CMB2 item for the REST response.
252
	 *
253
	 * @since 2.2.4
254
	 *
255
	 * @param  mixed            $item     WordPress representation of the item.
0 ignored issues
show
Bug introduced by
There is no parameter named $item. 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...
256
	 * @param  WP_REST_Request  $request  Request object.
257
	 * @return WP_REST_Response $response
258
	 */
259
	public function prepare_item_for_response( $data, $request = null ) {
260
		$data = $this->filter_response_by_context( $data, $this->request['context'] );
261
262
		/**
263
		 * Filter the prepared CMB2 item response.
264
		 *
265
		 * @since 2.2.4
266
		 *
267
		 * @param mixed  $data           Prepared data
268
		 * @param object $request        The WP_REST_Request object
269
		 * @param object $cmb2_endpoints This endpoints object
270
		 */
271
		return apply_filters( 'cmb2_rest_prepare', rest_ensure_response( $data ), $this->request, $this );
272
	}
273
274
	/**
275
	 * Initiates the request property and the rest_box property if box is readable.
276
	 *
277
	 * @since  2.2.4
278
	 *
279
	 * @param  WP_REST_Request $request      Request object.
280
	 * @param  string          $request_type A description of the type of request being made.
281
	 *
282
	 * @return void
283
	 */
284 View Code Duplication
	protected function initiate_rest_read_box( $request, $request_type ) {
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...
285
		$this->initiate_rest_box( $request, $request_type );
286
287
		if ( ! is_wp_error( $this->rest_box ) && ! $this->rest_box->rest_read ) {
0 ignored issues
show
Documentation introduced by
The property $rest_read is declared protected in CMB2_REST. Since you implemented __get(), maybe consider adding a @property or @property-read annotation. This makes it easier for IDEs to provide auto-completion.

Since your code implements the magic setter _set, this function will be called for any write access on an undefined variable. You can add the @property annotation to your class or interface to document the existence of this variable.

<?php

/**
 * @property int $x
 * @property int $y
 * @property string $text
 */
class MyLabel
{
    private $properties;

    private $allowedProperties = array('x', 'y', 'text');

    public function __get($name)
    {
        if (isset($properties[$name]) && in_array($name, $this->allowedProperties)) {
            return $properties[$name];
        } else {
            return null;
        }
    }

    public function __set($name, $value)
    {
        if (in_array($name, $this->allowedProperties)) {
            $properties[$name] = $value;
        } else {
            throw new \LogicException("Property $name is not defined.");
        }
    }

}

Since the property has write access only, you can use the @property-write annotation instead.

Of course, you may also just have mistyped another name, in which case you should fix the error.

See also the PhpDoc documentation for @property.

Loading history...
288
			$this->rest_box = new WP_Error( 'cmb2_rest_no_read_error', __( 'This box does not have read permissions.', 'cmb2' ), array( 'status' => 403 ) );
0 ignored issues
show
Documentation Bug introduced by
It seems like new \WP_Error('cmb2_rest...array('status' => 403)) of type object<WP_Error> is incompatible with the declared type object<CMB2_REST> of property $rest_box.

Our type inference engine has found an assignment to a property that is incompatible with the declared type of that property.

Either this assignment is in error or the assigned type should be added to the documentation/type hint for that property..

Loading history...
289
		}
290
	}
291
292
	/**
293
	 * Initiates the request property and the rest_box property if box is writeable.
294
	 *
295
	 * @since  2.2.4
296
	 *
297
	 * @param  WP_REST_Request $request      Request object.
298
	 * @param  string          $request_type A description of the type of request being made.
299
	 *
300
	 * @return void
301
	 */
302 View Code Duplication
	protected function initiate_rest_edit_box( $request, $request_type ) {
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...
303
		$this->initiate_rest_box( $request, $request_type );
304
305
		if ( ! is_wp_error( $this->rest_box ) && ! $this->rest_box->rest_edit ) {
0 ignored issues
show
Documentation introduced by
The property $rest_edit is declared protected in CMB2_REST. Since you implemented __get(), maybe consider adding a @property or @property-read annotation. This makes it easier for IDEs to provide auto-completion.

Since your code implements the magic setter _set, this function will be called for any write access on an undefined variable. You can add the @property annotation to your class or interface to document the existence of this variable.

<?php

/**
 * @property int $x
 * @property int $y
 * @property string $text
 */
class MyLabel
{
    private $properties;

    private $allowedProperties = array('x', 'y', 'text');

    public function __get($name)
    {
        if (isset($properties[$name]) && in_array($name, $this->allowedProperties)) {
            return $properties[$name];
        } else {
            return null;
        }
    }

    public function __set($name, $value)
    {
        if (in_array($name, $this->allowedProperties)) {
            $properties[$name] = $value;
        } else {
            throw new \LogicException("Property $name is not defined.");
        }
    }

}

Since the property has write access only, you can use the @property-write annotation instead.

Of course, you may also just have mistyped another name, in which case you should fix the error.

See also the PhpDoc documentation for @property.

Loading history...
306
			$this->rest_box = new WP_Error( 'cmb2_rest_no_write_error', __( 'This box does not have write permissions.', 'cmb2' ), array( 'status' => 403 ) );
0 ignored issues
show
Documentation Bug introduced by
It seems like new \WP_Error('cmb2_rest...array('status' => 403)) of type object<WP_Error> is incompatible with the declared type object<CMB2_REST> of property $rest_box.

Our type inference engine has found an assignment to a property that is incompatible with the declared type of that property.

Either this assignment is in error or the assigned type should be added to the documentation/type hint for that property..

Loading history...
307
		}
308
	}
309
310
	/**
311
	 * Initiates the request property and the rest_box property.
312
	 *
313
	 * @since  2.2.4
314
	 *
315
	 * @param  WP_REST_Request $request      Request object.
316
	 * @param  string          $request_type A description of the type of request being made.
317
	 *
318
	 * @return void
319
	 */
320
	protected function initiate_rest_box( $request, $request_type ) {
321
		$this->initiate_request( $request, $request_type );
322
323
		$this->rest_box = CMB2_REST::get_rest_box( $this->request->get_param( 'cmb_id' ) );
0 ignored issues
show
Documentation Bug introduced by
It seems like \CMB2_REST::get_rest_box...t->get_param('cmb_id')) can also be of type false. However, the property $rest_box is declared as type object<CMB2_REST>. Maybe add an additional type check?

Our type inference engine has found a suspicous assignment of a value to a property. This check raises an issue when a value that can be of a mixed type is assigned to a property that is type hinted more strictly.

For example, imagine you have a variable $accountId that can either hold an Id object or false (if there is no account id yet). Your code now assigns that value to the id property of an instance of the Account class. This class holds a proper account, so the id value must no longer be false.

Either this assignment is in error or a type check should be added for that assignment.

class Id
{
    public $id;

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

}

class Account
{
    /** @var  Id $id */
    public $id;
}

$account_id = false;

if (starsAreRight()) {
    $account_id = new Id(42);
}

$account = new Account();
if ($account instanceof Id)
{
    $account->id = $account_id;
}
Loading history...
324
325
		if ( ! $this->rest_box ) {
326
327
			$this->rest_box = new WP_Error( 'cmb2_rest_box_not_found_error', __( 'No box found by that id. A box needs to be registered with the "show_in_rest" parameter configured.', 'cmb2' ), array( 'status' => 403 ) );
0 ignored issues
show
Documentation Bug introduced by
It seems like new \WP_Error('cmb2_rest...array('status' => 403)) of type object<WP_Error> is incompatible with the declared type object<CMB2_REST> of property $rest_box.

Our type inference engine has found an assignment to a property that is incompatible with the declared type of that property.

Either this assignment is in error or the assigned type should be added to the documentation/type hint for that property..

Loading history...
328
329
		} else {
330
331 View Code Duplication
			if ( isset( $this->request['object_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...
332
				$this->rest_box->cmb->object_id( sanitize_text_field( $this->request['object_id'] ) );
333
			}
334
335 View Code Duplication
			if ( isset( $this->request['object_type'] ) ) {
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...
336
				$this->rest_box->cmb->object_type( sanitize_text_field( $this->request['object_type'] ) );
337
			}
338
		}
339
	}
340
341
	/**
342
	 * Initiates the request property and sets up the initial static properties.
343
	 *
344
	 * @since  2.2.4
345
	 *
346
	 * @param  WP_REST_Request $request      Request object.
347
	 * @param  string          $request_type A description of the type of request being made.
348
	 *
349
	 * @return void
350
	 */
351
	public function initiate_request( $request, $request_type ) {
352
		$this->request = $request;
353
354
		if ( ! isset( $this->request['context'] ) || empty( $this->request['context'] ) ) {
355
			$this->request['context'] = 'view';
356
		}
357
358
		if ( ! self::$request_type ) {
359
			self::$request_type = $request_type;
360
		}
361
362
		if ( ! self::$route ) {
363
			self::$route = $this->request->get_route();
364
		}
365
	}
366
367
	/**
368
	 * Useful when getting `_embed`-ed items
369
	 *
370
	 * @since  2.2.4
371
	 *
372
	 * @return string  Initial requested type.
373
	 */
374
	public static function get_intial_request_type() {
375
		return self::$request_type;
376
	}
377
378
	/**
379
	 * Useful when getting `_embed`-ed items
380
	 *
381
	 * @since  2.2.4
382
	 *
383
	 * @return string  Initial requested route.
384
	 */
385
	public static function get_intial_route() {
386
		return self::$route;
387
	}
388
389
	/**
390
	 * Get CMB2 fields schema, conforming to JSON Schema
391
	 *
392
	 * @since 2.2.4
393
	 *
394
	 * @return array
395
	 */
396
	public function get_item_schema() {
397
		$schema = array(
398
			'$schema'              => 'http://json-schema.org/draft-04/schema#',
399
			'title'                => 'CMB2',
400
			'type'                 => 'object',
401
			'properties'           => array(
402
				'description' => array(
403
					'description'  => 'A human-readable description of the object.',
404
					'type'         => 'string',
405
					'context'      => array( 'view' ),
406
					),
407
					'name'             => array(
408
						'description'  => 'The id for the object.',
409
						'type'         => 'integer',
410
						'context'      => array( 'view' ),
411
					),
412
				'name' => array(
413
					'description'  => 'The title for the object.',
414
					'type'         => 'string',
415
					'context'      => array( 'view' ),
416
				),
417
			),
418
		);
419
420
		return $this->add_additional_fields_schema( $schema );
421
	}
422
423
	/**
424
	 * Return an array of contextual links for endpoint/object
425
	 * @link http://v2.wp-api.org/extending/linking/
426
	 * @link http://www.iana.org/assignments/link-relations/link-relations.xhtml
427
	 *
428
	 * @since  2.2.4
429
	 *
430
	 * @param  mixed  $object Object to build links from.
431
	 *
432
	 * @return array          Array of links
433
	 */
434
	abstract protected function prepare_links( $object );
435
436
	/**
437
	 * Get whitelisted query strings from URL for appending to link URLS.
438
	 *
439
	 * @since  2.2.4
440
	 *
441
	 * @return string URL query stringl
442
	 */
443
	public function get_query_string() {
444
		$defaults = array(
445
			'object_id'   => 0,
446
			'object_type' => '',
447
			'_rendered'   => '',
448
			// '_embed'      => '',
0 ignored issues
show
Unused Code Comprehensibility introduced by
58% 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...
449
		);
450
451
		$query_string = '';
452
453
		foreach ( $defaults as $key => $value ) {
454
			if ( isset( $this->request[ $key ] ) ) {
455
				$query_string .= $query_string ? '&' : '?';
456
				$query_string .= $key;
457
				if ( $value = sanitize_text_field( $this->request[ $key ] ) ) {
458
					$query_string .= '=' . $value;
459
				}
460
			}
461
		}
462
463
		return $query_string;
464
	}
465
466
}
467