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

CMB2_REST_Controller::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 1
eloc 2
c 1
b 0
f 0
nc 1
nop 1
dl 0
loc 3
rs 10
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::NAMESPACE;
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, 'permissions_check' );
105
106
		/**
107
		 * By default, no special permissions needed.
108
		 *
109
		 * @since 2.2.4
110
		 *
111
		 * @param bool   $can_access Whether this CMB2 endpoint can be accessed.
112
		 * @param object $request    The WP_REST_Request object
113
		 */
114
		return apply_filters( 'cmb2_request_items_permissions_check', true, $this->request );
115
	}
116
117
	/**
118
	 * Check if a given request has access to a field or box.
119
	 * By default, no special permissions needed, but filtering return value.
120
	 *
121
	 * @since 2.2.4
122
	 *
123
	 * @param  WP_REST_Request $request Full details about the request.
124
	 * @return WP_Error|boolean
125
	 */
126
	public function get_item_permissions_check( $request ) {
127
		$this->initiate_request( $request, 'permissions_check' );
128
129
		/**
130
		 * By default, no special permissions needed.
131
		 *
132
		 * @since 2.2.4
133
		 *
134
		 * @param bool   $can_access Whether this CMB2 endpoint can be accessed.
135
		 * @param object $request    The WP_REST_Request object
136
		 */
137
		return apply_filters( 'cmb2_request_item_permissions_check', true, $this->request );
138
	}
139
140
	/**
141
	 * Prepare a CMB2 object for serialization
142
	 *
143
	 * @since 2.2.4
144
	 *
145
	 * @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...
146
	 * @return array $data
147
	 */
148
	public function prepare_item( $post ) {
149
		return $this->prepare_item_for_response( $post, $this->request );
150
	}
151
152
	/**
153
	 * Output buffers a callback and returns the results.
154
	 *
155
	 * @since  2.2.4
156
	 *
157
	 * @param  mixed $cb Callable function/method.
158
	 * @return mixed     Results of output buffer after calling function/method.
159
	 */
160
	public function get_cb_results( $cb ) {
161
		$args = func_get_args();
162
		array_shift( $args ); // ignore $cb
163
		ob_start();
164
		call_user_func_array( $cb, $args );
165
166
		return ob_get_clean();
167
	}
168
169
	/**
170
	 * Prepare the CMB2 item for the REST response.
171
	 *
172
	 * @since 2.2.4
173
	 *
174
	 * @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...
175
	 * @param  WP_REST_Request  $request  Request object.
176
	 * @return WP_REST_Response $response
177
	 */
178
	public function prepare_item_for_response( $data, $request = null ) {
179
		$data = $this->filter_response_by_context( $data, $this->request['context'] );
180
181
		/**
182
		 * Filter the prepared CMB2 item response.
183
		 *
184
		 * @since 2.2.4
185
		 *
186
		 * @param mixed  $data           Prepared data
187
		 * @param object $request        The WP_REST_Request object
188
		 * @param object $cmb2_endpoints This endpoints object
189
		 */
190
		return apply_filters( 'cmb2_rest_prepare', rest_ensure_response( $data ), $this->request, $this );
191
	}
192
193
	/**
194
	 * Initiates the request property and the rest_box property if box is readable.
195
	 *
196
	 * @since  2.2.4
197
	 *
198
	 * @param  WP_REST_Request $request      Request object.
199
	 * @param  string          $request_type A description of the type of request being made.
200
	 *
201
	 * @return void
202
	 */
203 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...
204
		$this->initiate_rest_box( $request, $request_type );
205
206
		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...
207
			$this->rest_box = new WP_Error( 'cmb2_rest_error', __( 'This box does not have read permissions.', 'cmb2' ) );
0 ignored issues
show
Documentation Bug introduced by
It seems like new \WP_Error('cmb2_rest...permissions.', 'cmb2')) 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...
208
		}
209
	}
210
211
	/**
212
	 * Initiates the request property and the rest_box property if box is writeable.
213
	 *
214
	 * @since  2.2.4
215
	 *
216
	 * @param  WP_REST_Request $request      Request object.
217
	 * @param  string          $request_type A description of the type of request being made.
218
	 *
219
	 * @return void
220
	 */
221 View Code Duplication
	protected function initiate_rest_write_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...
222
		$this->initiate_rest_box( $request, $request_type );
223
224
		if ( ! is_wp_error( $this->rest_box ) && ! $this->rest_box->rest_write ) {
0 ignored issues
show
Documentation introduced by
The property $rest_write 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...
225
			$this->rest_box = new WP_Error( 'cmb2_rest_error', __( 'This box does not have write permissions.', 'cmb2' ) );
0 ignored issues
show
Documentation Bug introduced by
It seems like new \WP_Error('cmb2_rest...permissions.', 'cmb2')) 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...
226
		}
227
	}
228
229
	/**
230
	 * Initiates the request property and the rest_box property.
231
	 *
232
	 * @since  2.2.4
233
	 *
234
	 * @param  WP_REST_Request $request      Request object.
235
	 * @param  string          $request_type A description of the type of request being made.
236
	 *
237
	 * @return void
238
	 */
239
	protected function initiate_rest_box( $request, $request_type ) {
240
		$this->initiate_request( $request, $request_type );
241
242
		$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...
243
244
		if ( ! $this->rest_box ) {
245
246
			$this->rest_box = new WP_Error( 'cmb2_rest_error', __( 'No box found by that id. A box needs to be registered with the "show_in_rest" parameter configured.', 'cmb2' ) );
0 ignored issues
show
Documentation Bug introduced by
It seems like new \WP_Error('cmb2_rest... configured.', 'cmb2')) 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...
247
248
		} else {
249
250
			if ( isset( $this->request['object_id'] ) ) {
251
				$this->rest_box->cmb->object_id( absint( $this->request['object_id'] ) );
252
			}
253
254
			if ( isset( $this->request['object_type'] ) ) {
255
				$this->rest_box->cmb->object_type( sanitize_text_field( $this->request['object_type'] ) );
256
			}
257
		}
258
	}
259
260
	/**
261
	 * Initiates the request property and sets up the initial static properties.
262
	 *
263
	 * @since  2.2.4
264
	 *
265
	 * @param  WP_REST_Request $request      Request object.
266
	 * @param  string          $request_type A description of the type of request being made.
267
	 *
268
	 * @return void
269
	 */
270
	public function initiate_request( $request, $request_type ) {
271
		$this->request = $request;
272
273
		if ( ! isset( $this->request['context'] ) || empty( $this->request['context'] ) ) {
274
			$this->request['context'] = 'view';
275
		}
276
277
		if ( ! self::$request_type ) {
278
			self::$request_type = $request_type;
279
		}
280
281
		if ( ! self::$route ) {
282
			self::$route = $this->request->get_route();
283
		}
284
	}
285
286
	/**
287
	 * Useful when getting `_embed`-ed items
288
	 *
289
	 * @since  2.2.4
290
	 *
291
	 * @return string  Initial requested type.
292
	 */
293
	public static function get_intial_request_type() {
294
		return self::$request_type;
295
	}
296
297
	/**
298
	 * Useful when getting `_embed`-ed items
299
	 *
300
	 * @since  2.2.4
301
	 *
302
	 * @return string  Initial requested route.
303
	 */
304
	public static function get_intial_route() {
305
		return self::$route;
306
	}
307
308
	/**
309
	 * Get CMB2 fields schema, conforming to JSON Schema
310
	 *
311
	 * @since 2.2.4
312
	 *
313
	 * @return array
314
	 */
315
	public function get_item_schema() {
316
		$schema = array(
317
			'$schema'              => 'http://json-schema.org/draft-04/schema#',
318
			'title'                => 'CMB2',
319
			'type'                 => 'object',
320
			'properties'           => array(
321
				'description' => array(
322
					'description'  => 'A human-readable description of the object.',
323
					'type'         => 'string',
324
					'context'      => array( 'view' ),
325
					),
326
					'name'             => array(
327
						'description'  => 'The id for the object.',
328
						'type'         => 'integer',
329
						'context'      => array( 'view' ),
330
					),
331
				'name' => array(
332
					'description'  => 'The title for the object.',
333
					'type'         => 'string',
334
					'context'      => array( 'view' ),
335
				),
336
			),
337
		);
338
339
		return $this->add_additional_fields_schema( $schema );
340
	}
341
342
	/**
343
	 * Return an array of contextual links for endpoint/object
344
	 * @link http://v2.wp-api.org/extending/linking/
345
	 * @link http://www.iana.org/assignments/link-relations/link-relations.xhtml
346
	 *
347
	 * @since  2.2.4
348
	 *
349
	 * @param  mixed  $object Object to build links from.
350
	 *
351
	 * @return array          Array of links
352
	 */
353
	abstract protected function prepare_links( $object );
354
355
	/**
356
	 * Get whitelisted query strings from URL for appending to link URLS.
357
	 *
358
	 * @since  2.2.4
359
	 *
360
	 * @return string URL query stringl
361
	 */
362
	public function get_query_string() {
363
		$defaults = array(
364
			'object_id'   => 0,
365
			'object_type' => '',
366
			'_rendered'   => '',
367
			// '_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...
368
		);
369
370
		$query_string = '';
371
372
		foreach ( $defaults as $key => $value ) {
373
			if ( isset( $this->request[ $key ] ) ) {
374
				$query_string .= $query_string ? '&' : '?';
375
				$query_string .= $key;
376
				if ( $value = sanitize_text_field( $this->request[ $key ] ) ) {
377
					$query_string .= '=' . $value;
378
				}
379
			}
380
		}
381
382
		return $query_string;
383
	}
384
385
}
386