Completed
Pull Request — trunk (#541)
by Justin
22:39 queued 06:07
created

CMB2_REST_Controller::get_cb_results()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 8
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Importance

Changes 3
Bugs 0 Features 0
Metric Value
cc 1
eloc 6
c 3
b 0
f 0
nc 1
nop 1
dl 0
loc 8
rs 9.4285
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
	 * The initial route
49
	 * @var   string
50
	 * @since 2.2.0
51
	 */
52
	protected static $route = '';
53
54
	/**
55
	 * Defines which endpoint the initial request is.
56
	 * @var string $request_type
57
	 * @since 2.2.0
58
	 */
59
	protected static $request_type = '';
60
61
	/**
62
	 * Constructor
63
	 * @since 2.2.0
64
	 */
65
	public function __construct( WP_REST_Server $wp_rest_server ) {
66
		$this->server = $wp_rest_server;
67
	}
68
69
	/**
70
	 * Check if a given request has access to a field or box.
71
	 * By default, no special permissions needed, but filtering return value.
72
	 *
73
	 * @since 2.2.0
74
	 *
75
	 * @param  WP_REST_Request $request Full details about the request.
76
	 * @return bool
77
	 */
78
	public function get_item_permissions_check( $request ) {
79
		$this->initiate_request( $request, 'permissions_check' );
80
81
		/**
82
		 * By default, no special permissions needed.
83
		 *
84
		 * @since 2.2.0
85
		 *
86
		 * @param object $request        The WP_REST_Request object
87
		 * @param object $cmb2_endpoints This endpoints object
88
		 */
89
		return apply_filters( 'cmb2_request_permissions_check', true, $this->request );
90
	}
91
92
	/**
93
	 * Prepare a CMB2 object for serialization
94
	 *
95
	 * @since 2.2.0
96
	 *
97
	 * @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...
98
	 * @return array $data
99
	 */
100
	public function prepare_item( $post ) {
101
		return $this->prepare_item_for_response( $post, $this->request );
102
	}
103
104
	/**
105
	 * Output buffers a callback and returns the results.
106
	 *
107
	 * @since  2.2.0
108
	 *
109
	 * @param  mixed $cb Callable function/method.
110
	 * @return mixed     Results of output buffer after calling function/method.
111
	 */
112
	public function get_cb_results( $cb ) {
113
		$args = func_get_args();
114
		array_shift( $args ); // ignore $cb
115
		ob_start();
116
		call_user_func_array( $cb, $args );
117
118
		return ob_get_clean();
119
	}
120
121
	/**
122
	 * Prepare a CMB2 object for serialization
123
	 *
124
	 * @since 2.2.0
125
	 *
126
	 * @param  mixed           $data
127
	 * @param  WP_REST_Request $request Request object
128
	 * @return array $data
129
	 */
130
	public function prepare_item_for_response( $data, $request = null ) {
131
		$data = $this->filter_response_by_context( $data, $this->request['context'] );
132
133
		/**
134
		 * Filter the prepared CMB2 item response.
135
		 *
136
		 * @since 2.2.0
137
		 *
138
		 * @param mixed  $data           Prepared data
139
		 * @param object $request        The WP_REST_Request object
140
		 * @param object $cmb2_endpoints This endpoints object
141
		 */
142
		return apply_filters( 'cmb2_rest_prepare', rest_ensure_response( $data ), $this->request, $this );
143
	}
144
145 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...
146
		$this->initiate_rest_box( $request, $request_type );
147
148
		if ( ! is_wp_error( $this->rest_box ) && ! $this->rest_box->rest_read ) {
149
			$this->rest_box = new WP_Error( 'cmb2_rest_error', __( 'This box does not have read permissions.', 'cmb2' ) );
150
		}
151
	}
152
153 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...
154
		$this->initiate_rest_box( $request, $request_type );
155
156
		if ( ! is_wp_error( $this->rest_box ) && ! $this->rest_box->rest_write ) {
157
			$this->rest_box = new WP_Error( 'cmb2_rest_error', __( 'This box does not have write permissions.', 'cmb2' ) );
158
		}
159
	}
160
161
	protected function initiate_rest_box( $request, $request_type ) {
162
		$this->initiate_request( $request, $request_type );
163
164
		$this->rest_box = CMB2_REST::get_rest_box( $this->request->get_param( 'cmb_id' ) );
165
166
		if ( ! $this->rest_box ) {
167
			$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' ) );
168
		}
169
	}
170
171
	public function initiate_request( $request, $request_type ) {
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...
172
		$this->request = $request;
173
		$this->request['context'] = isset( $this->request['context'] ) && ! empty( $this->request['context'] )
174
			? $this->request['context']
175
			: 'view';
176
177
		if ( isset( $_REQUEST['object_id'] ) ) {
178
			$this->object_id = absint( $_REQUEST['object_id'] );
179
		}
180
181
		if ( isset( $_REQUEST['object_type'] ) ) {
182
			$this->object_type = absint( $_REQUEST['object_type'] );
183
		}
184
185
		self::$request_type = self::$request_type ? self::$request_type : $request_type;
186
		self::$route = self::$route ? self::$route : $this->request->get_route();
0 ignored issues
show
Bug introduced by
The method get_route cannot be called on $this->request (of type array<string,?,{"context":"?"}>).

Methods can only be called on objects. This check looks for methods being called on variables that have been inferred to never be objects.

Loading history...
187
	}
188
189
	public static function get_intial_request_type() {
190
		return self::$request_type;
191
	}
192
193
	public static function get_intial_route() {
194
		return self::$route;
195
	}
196
197
	/**
198
	 * Get CMB2 fields schema, conforming to JSON Schema
199
	 *
200
	 * @since 2.2.0
201
	 *
202
	 * @return array
203
	 */
204
	public function get_item_schema() {
205
		$schema = array(
206
			'$schema'              => 'http://json-schema.org/draft-04/schema#',
207
			'title'                => 'CMB2',
208
			'type'                 => 'object',
209
			'properties'           => array(
210
				'description' => array(
211
					'description'  => 'A human-readable description of the object.',
212
					'type'         => 'string',
213
					'context'      => array( 'view' ),
214
					),
215
					'name'             => array(
216
						'description'  => 'The id for the object.',
217
						'type'         => 'integer',
218
						'context'      => array( 'view' ),
219
					),
220
				'name' => array(
221
					'description'  => 'The title for the object.',
222
					'type'         => 'string',
223
					'context'      => array( 'view' ),
224
				),
225
			),
226
		);
227
228
		return $this->add_additional_fields_schema( $schema );
229
	}
230
231
	/**
232
	 * Return an array of contextual links for endpoint/object
233
	 * @link http://v2.wp-api.org/extending/linking/
234
	 * @link http://www.iana.org/assignments/link-relations/link-relations.xhtml
235
	 *
236
	 * @since  2.2.0
237
	 *
238
	 * @param  mixed  $object Object to build links from.
239
	 *
240
	 * @return array          Array of links
241
	 */
242
	abstract protected function prepare_links( $object );
243
244
}
245