Completed
Push — trunk ( b974f1...832514 )
by Justin
06:32
created

get_items_permissions_check()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 13
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 3
nc 1
nop 1
dl 0
loc 13
rs 9.4285
c 0
b 0
f 0
1
<?php
2
/**
3
 * CMB2 objects/boxes endpoint for WordPres REST API.
4
 * Allows access to boxes configuration data.
5
 *
6
 * @todo  Add better documentation.
7
 * @todo  Research proper schema.
8
 *
9
 * @since 2.2.3
10
 *
11
 * @category  WordPress_Plugin
12
 * @package   CMB2
13
 * @author    WebDevStudios
14
 * @license   GPL-2.0+
15
 * @link      http://webdevstudios.com
16
 */
17
class CMB2_REST_Controller_Boxes extends CMB2_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 base of this controller's route.
21
	 *
22
	 * @var string
23
	 */
24
	protected $rest_base = 'boxes';
25
26
	/**
27
	 * The combined $namespace and $rest_base for these routes.
28
	 *
29
	 * @var string
30
	 */
31
	protected $namespace_base = '';
32
33
	/**
34
	 * Constructor
35
	 * @since 2.2.3
36
	 */
37
	public function __construct( WP_REST_Server $wp_rest_server ) {
38
		$this->namespace_base = $this->namespace . '/' . $this->rest_base;
39
		parent::__construct( $wp_rest_server );
40
	}
41
42
	/**
43
	 * Register the routes for the objects of the controller.
44
	 *
45
	 * @since 2.2.3
46
	 */
47
	public function register_routes() {
48
		$args = array(
49
			'_embed' => array(
50
				'description' => __( 'Includes the registered fields for the box in the response.', 'cmb2' ),
51
			),
52
		);
53
54
		// @todo determine what belongs in the context param.
55
		// $args['context'] = $this->get_context_param();
0 ignored issues
show
Unused Code Comprehensibility introduced by
65% 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...
56
		// $args['context']['required'] = false;
0 ignored issues
show
Unused Code Comprehensibility introduced by
70% 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...
57
		// $args['context']['default'] = 'view';
0 ignored issues
show
Unused Code Comprehensibility introduced by
70% 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...
58
		// $args['context']['enum'] = array( 'view', 'embed' );
0 ignored issues
show
Unused Code Comprehensibility introduced by
67% 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...
59
60
		// Returns all boxes data.
61
		register_rest_route( $this->namespace, '/' . $this->rest_base, array(
62
			array(
63
				'methods'             => WP_REST_Server::READABLE,
64
				'permission_callback' => array( $this, 'get_items_permissions_check' ),
65
				'callback'            => array( $this, 'get_items' ),
66
				'args'                => $args,
67
			),
68
			'schema' => array( $this, 'get_item_schema' ),
69
		) );
70
71
		$args['_rendered'] = array(
72
			'description' => __( 'Includes the fully rendered attributes, \'form_open\', \'form_close\', as well as the enqueued \'js_dependencies\' script handles, and \'css_dependencies\' stylesheet handles.', 'cmb2' ),
73
		);
74
75
		// Returns specific box's data.
76
		register_rest_route( $this->namespace, '/' . $this->rest_base . '/(?P<cmb_id>[\w-]+)', array(
77
			array(
78
				'methods'             => WP_REST_Server::READABLE,
79
				'permission_callback' => array( $this, 'get_item_permissions_check' ),
80
				'callback'            => array( $this, 'get_item' ),
81
				'args'                => $args,
82
			),
83
			'schema' => array( $this, 'get_item_schema' ),
84
		) );
85
	}
86
87
	/**
88
	 * Check if a given request has access to get boxes.
89
	 *
90
	 * @since 2.2.3
91
	 *
92
	 * @param  WP_REST_Request $request Full data about the request.
93
	 * @return WP_Error|boolean
94
	 */
95
	public function get_items_permissions_check( $request ) {
96
		$this->initiate_request( $request, __FUNCTION__ );
97
98
		/**
99
		 * By default, no special permissions needed.
100
		 *
101
		 * @since 2.2.3
102
		 *
103
		 * @param bool   $can_access Whether this CMB2 endpoint can be accessed.
104
		 * @param object $controller This CMB2_REST_Controller object.
105
		 */
106
		return apply_filters( 'cmb2_api_get_boxes_permissions_check', true, $this );
107
	}
108
109
	/**
110
	 * Get all public CMB2 boxes.
111
	 *
112
	 * @since 2.2.3
113
	 *
114
	 * @param  WP_REST_Request $request Full data about the request.
115
	 * @return WP_Error|WP_REST_Response
116
	 */
117
	public function get_items( $request ) {
118
		$this->initiate_request( $request, 'boxes_read' );
119
120
		$boxes = CMB2_REST::get_all();
121
		if ( empty( $boxes ) ) {
122
			return new WP_Error( 'cmb2_rest_no_boxes', __( 'No boxes found.', 'cmb2' ), array( 'status' => 403 ) );
123
		}
124
125
		$boxes_data = array();
126
127
		// Loop and prepare boxes data.
128
		foreach ( $boxes as $this->rest_box ) {
129 View Code Duplication
			if (
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...
130
				// Make sure this box can be read
131
				$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...
132
				// And make sure current user can view this box.
133
				&& $this->get_item_permissions_check_filter( $this->request )
134
			) {
135
				$boxes_data[] = $this->server->response_to_data(
136
					$this->get_rest_box(),
137
					isset( $this->request['_embed'] )
138
				);
139
			}
140
		}
141
142
		return $this->prepare_item( $boxes_data );
143
	}
144
145
	/**
146
	 * Check if a given request has access to a box.
147
	 * By default, no special permissions needed, but filtering return value.
148
	 *
149
	 * @since 2.2.3
150
	 *
151
	 * @param  WP_REST_Request $request Full details about the request.
152
	 * @return WP_Error|boolean
153
	 */
154
	public function get_item_permissions_check( $request ) {
155
		$this->initiate_rest_read_box( $request, 'box_read' );
156
157
		return $this->get_item_permissions_check_filter();
158
	}
159
160
	/**
161
	 * Check by filter if a given request has access to a box.
162
	 * By default, no special permissions needed, but filtering return value.
163
	 *
164
	 * @since 2.2.3
165
	 *
166
	 * @param  bool $can_access Whether the current request has access to view the box by default.
167
	 * @return WP_Error|boolean
168
	 */
169
	public function get_item_permissions_check_filter( $can_access = true ) {
0 ignored issues
show
Unused Code introduced by
The parameter $can_access is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
170
		$can_access = true;
171
172
		/**
173
		 * By default, no special permissions needed.
174
		 *
175
		 * @since 2.2.3
176
		 *
177
		 * @param bool   $can_access Whether this CMB2 endpoint can be accessed.
178
		 * @param object $controller This CMB2_REST_Controller object.
179
		 */
180
		return $this->maybe_hook_callback_and_apply_filters( 'cmb2_api_get_box_permissions_check', $can_access );
0 ignored issues
show
Documentation introduced by
$can_access is of type boolean, but the function expects a string.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
181
	}
182
183
	/**
184
	 * Get one CMB2 box from the collection.
185
	 *
186
	 * @since 2.2.3
187
	 *
188
	 * @param  WP_REST_Request $request Full data about the request.
189
	 * @return WP_Error|WP_REST_Response
190
	 */
191
	public function get_item( $request ) {
192
		$this->initiate_rest_read_box( $request, 'box_read' );
193
194
		if ( is_wp_error( $this->rest_box ) ) {
195
			return $this->rest_box;
0 ignored issues
show
Bug Best Practice introduced by
The return type of return $this->rest_box; (CMB2_REST) is incompatible with the return type of the parent method WP_REST_Controller::get_item of type WP_Error|WP_REST_Response.

If you return a value from a function or method, it should be a sub-type of the type that is given by the parent type f.e. an interface, or abstract method. This is more formally defined by the Lizkov substitution principle, and guarantees that classes that depend on the parent type can use any instance of a child type interchangably. This principle also belongs to the SOLID principles for object oriented design.

Let’s take a look at an example:

class Author {
    private $name;

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

    public function getName() {
        return $this->name;
    }
}

abstract class Post {
    public function getAuthor() {
        return 'Johannes';
    }
}

class BlogPost extends Post {
    public function getAuthor() {
        return new Author('Johannes');
    }
}

class ForumPost extends Post { /* ... */ }

function my_function(Post $post) {
    echo strtoupper($post->getAuthor());
}

Our function my_function expects a Post object, and outputs the author of the post. The base class Post returns a simple string and outputting a simple string will work just fine. However, the child class BlogPost which is a sub-type of Post instead decided to return an object, and is therefore violating the SOLID principles. If a BlogPost were passed to my_function, PHP would not complain, but ultimately fail when executing the strtoupper call in its body.

Loading history...
196
		}
197
198
		return $this->prepare_item( $this->get_rest_box() );
199
	}
200
201
	/**
202
	 * Get a CMB2 box prepared for REST
203
	 *
204
	 * @since 2.2.3
205
	 *
206
	 * @return array
207
	 */
208
	public function get_rest_box() {
209
		$cmb = $this->rest_box->cmb;
210
211
		$boxes_data = $cmb->meta_box;
212
213
		if ( isset( $this->request['_rendered'] ) && $this->namespace_base !== ltrim( CMB2_REST_Controller::get_intial_route(), '/' ) ) {
214
			$boxes_data['form_open'] = $this->get_cb_results( array( $cmb, 'render_form_open' ) );
215
			$boxes_data['form_close'] = $this->get_cb_results( array( $cmb, 'render_form_close' ) );
216
217
			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...
218
			$before_css = $wp_styles->queue;
219
			$before_js = $wp_scripts->queue;
220
221
			CMB2_JS::enqueue();
222
223
			$boxes_data['js_dependencies'] = array_values( array_diff( $wp_scripts->queue, $before_js ) );
224
			$boxes_data['css_dependencies'] = array_values( array_diff( $wp_styles->queue, $before_css ) );
225
		}
226
227
		// TODO: look into 'embed' parameter.
228
		// http://demo.wp-api.org/wp-json/wp/v2/posts?_embed
229
		unset( $boxes_data['fields'] );
230
		// Handle callable properties.
231
		unset( $boxes_data['show_on_cb'] );
232
233
		$response = rest_ensure_response( $boxes_data );
234
235
		$response->add_links( $this->prepare_links( $cmb ) );
0 ignored issues
show
Documentation introduced by
$cmb is of type object<CMB2>, but the function expects a object<CMB2_REST>.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
236
237
		return $response;
238
	}
239
240
	/**
241
	 * Return an array of contextual links for box/boxes.
242
	 *
243
	 * @since  2.2.3
244
	 *
245
	 * @param  CMB2_REST $cmb CMB2_REST object to build links from.
246
	 *
247
	 * @return array          Array of links
248
	 */
249
	protected function prepare_links( $cmb ) {
250
		$boxbase      = $this->namespace_base . '/' . $cmb->cmb_id;
0 ignored issues
show
Documentation introduced by
The property cmb_id does not exist on object<CMB2_REST>. Since you implemented __get, maybe consider adding a @property annotation.

Since your code implements the magic getter _get, this function will be called for any read 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.");
        }
    }

}

If the property has read access only, you can use the @property-read 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...
251
		$query_string = $this->get_query_string();
252
253
		return array(
254
			// Standard Link Relations -- http://v2.wp-api.org/extending/linking/
255
			'self' => array(
256
				'href' => rest_url( $boxbase . $query_string ),
257
			),
258
			'collection' => array(
259
				'href' => rest_url( $this->namespace_base . $query_string ),
260
			),
261
			// Custom Link Relations -- http://v2.wp-api.org/extending/linking/
262
			// TODO URL should document relationship.
263
			'https://cmb2.io/fields' => array(
264
				'href' => rest_url( trailingslashit( $boxbase ) . 'fields' . $query_string ),
265
				'embeddable' => true,
266
			),
267
		);
268
	}
269
270
}
271