Completed
Pull Request — trunk (#541)
by Justin
28:03 queued 25:22
created

CMB2_REST_Controller_Boxes   A

Complexity

Total Complexity 12

Size/Duplication

Total Lines 185
Duplicated Lines 0 %

Coupling/Cohesion

Components 2
Dependencies 4

Test Coverage

Coverage 86.49%

Importance

Changes 0
Metric Value
dl 0
loc 185
ccs 64
cts 74
cp 0.8649
rs 10
c 0
b 0
f 0
wmc 12
lcom 2
cbo 4

6 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 4 1
B register_routes() 0 38 1
A get_items() 0 19 4
A get_item() 0 9 2
B get_rest_box() 0 31 3
A prepare_links() 0 20 1
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.4
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.4
36
	 */
37 1
	public function __construct( WP_REST_Server $wp_rest_server ) {
38 1
		$this->namespace_base = $this->namespace . '/' . $this->rest_base;
39 1
		parent::__construct( $wp_rest_server );
40 1
	}
41
42
	/**
43
	 * Register the routes for the objects of the controller.
44
	 *
45
	 * @since 2.2.4
46
	 */
47 1
	public function register_routes() {
48
		$args = array(
49
			'_embed' => array(
50 1
				'description' => __( 'Includes the registered fields for the box in the response.', 'cmb2' ),
51 1
			),
52
			'_rendered' => array(
53 1
				'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' ),
54 1
			),
55 1
		);
56
57
		// @todo determine what belongs in the context param.
58
		// $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...
59
		// $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...
60
		// $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...
61
		// $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...
62
63
		// Returns all boxes data.
64 1
		register_rest_route( $this->namespace, '/' . $this->rest_base, array(
65
			array(
66 1
				'methods'             => WP_REST_Server::READABLE,
67 1
				'callback'            => array( $this, 'get_items' ),
68 1
				'permission_callback' => array( $this, 'get_items_permissions_check' ),
69 1
				'args'                => $args,
70 1
			),
71 1
			'schema' => array( $this, 'get_item_schema' ),
72 1
		) );
73
74
		// Returns specific box's data.
75 1
		register_rest_route( $this->namespace, '/' . $this->rest_base . '/(?P<cmb_id>[\w-]+)', array(
76
			array(
77 1
				'methods'             => WP_REST_Server::READABLE,
78 1
				'callback'            => array( $this, 'get_item' ),
79 1
				'permission_callback' => array( $this, 'get_item_permissions_check' ),
80 1
				'args'                => $args,
81 1
			),
82 1
			'schema' => array( $this, 'get_item_schema' ),
83 1
		) );
84 1
	}
85
86
	/**
87
	 * Get all public CMB2 boxes.
88
	 *
89
	 * @since 2.2.4
90
	 *
91
	 * @param  WP_REST_Request $request Full data about the request.
92
	 * @return WP_Error|WP_REST_Response
93
	 */
94 1
	public function get_items( $request ) {
95 1
		$this->initiate_request( $request, 'boxes_read' );
96
97 1
		$boxes = CMB2_REST::get_all();
98 1
		if ( empty( $boxes ) ) {
99
			return new WP_Error( 'cmb2_rest_no_boxes', __( 'No boxes found.', 'cmb2' ), array( 'status' => 403 ) );
100
		}
101
102 1
		$boxes_data = array();
103
		// Loop boxes and get specific field.
104 1
		foreach ( $boxes as $this->rest_box ) {
105 1
			if ( $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...
106 1
				$rest_box = $this->get_rest_box();
107 1
				$boxes_data[] = $this->server->response_to_data( $rest_box, isset( $this->request['_embed'] ) );
108 1
			}
109 1
		}
110
111 1
		return $this->prepare_item( $boxes_data );
112
	}
113
114
	/**
115
	 * Get one CMB2 box from the collection.
116
	 *
117
	 * @since 2.2.4
118
	 *
119
	 * @param  WP_REST_Request $request Full data about the request.
120
	 * @return WP_Error|WP_REST_Response
121
	 */
122 1
	public function get_item( $request ) {
123 1
		$this->initiate_rest_read_box( $request, 'box_read' );
124
125 1
		if ( is_wp_error( $this->rest_box ) ) {
126 1
			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...
127
		}
128
129 1
		return $this->prepare_item( $this->get_rest_box() );
130
	}
131
132
	/**
133
	 * Get a CMB2 box prepared for REST
134
	 *
135
	 * @since 2.2.4
136
	 *
137
	 * @return array
138
	 */
139 2
	public function get_rest_box() {
140 2
		$cmb = $this->rest_box->cmb;
141
142 2
		$boxes_data = $cmb->meta_box;
143
144 2
		if ( isset( $this->request['_rendered'] ) && $this->namespace_base !== CMB2_REST_Controller::get_intial_route() ) {
145
			$boxes_data['form_open'] = $this->get_cb_results( array( $cmb, 'render_form_open' ) );
146
			$boxes_data['form_close'] = $this->get_cb_results( array( $cmb, 'render_form_close' ) );
147
148
			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...
149
			$before_css = $wp_styles->queue;
150
			$before_js = $wp_scripts->queue;
151
152
			CMB2_JS::enqueue();
153
154
			$boxes_data['js_dependencies'] = array_values( array_diff( $wp_scripts->queue, $before_js ) );
155
			$boxes_data['css_dependencies'] = array_values( array_diff( $wp_styles->queue, $before_css ) );
156
		}
157
158
		// TODO: look into 'embed' parameter.
159
		// http://demo.wp-api.org/wp-json/wp/v2/posts?_embed
160 2
		unset( $boxes_data['fields'] );
161
		// Handle callable properties.
162 2
		unset( $boxes_data['show_on_cb'] );
163
164 2
		$response = rest_ensure_response( $boxes_data );
165
166 2
		$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...
167
168 2
		return $response;
169
	}
170
171
	/**
172
	 * Return an array of contextual links for box/boxes.
173
	 *
174
	 * @since  2.2.4
175
	 *
176
	 * @param  CMB2_REST $cmb CMB2_REST object to build links from.
177
	 *
178
	 * @return array          Array of links
179
	 */
180 2
	protected function prepare_links( $cmb ) {
181 2
		$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...
182 2
		$query_string = $this->get_query_string();
183
184
		return array(
185
			// Standard Link Relations -- http://v2.wp-api.org/extending/linking/
186
			'self' => array(
187 2
				'href' => rest_url( $boxbase . $query_string ),
188 2
			),
189
			'collection' => array(
190 2
				'href' => rest_url( $this->namespace_base . $query_string ),
191 2
			),
192
			// Custom Link Relations -- http://v2.wp-api.org/extending/linking/
193
			// TODO URL should document relationship.
194
			'https://cmb2.io/fields' => array(
195 2
				'href' => rest_url( trailingslashit( $boxbase ) . 'fields' . $query_string ),
196 2
				'embeddable' => true,
197 2
			),
198 2
		);
199
	}
200
201
}
202