Completed
Pull Request — trunk (#541)
by Justin
08:25
created

CMB2_REST_Access::get_object_data()   C

Complexity

Conditions 8
Paths 12

Size

Total Lines 22
Code Lines 17

Duplication

Lines 0
Ratio 0 %
Metric Value
dl 0
loc 22
rs 6.6038
cc 8
eloc 17
nc 12
nop 1
1
<?php
2
/**
3
 * Handles hooking CMB2 objects/fields into the WordPres REST API
4
 * which can allow fields to be read and/or updated.
5
 *
6
 * @since  2.2.0
7
 *
8
 * @category  WordPress_Plugin
9
 * @package   CMB2
10
 * @author    WebDevStudios
11
 * @license   GPL-2.0+
12
 * @link      http://webdevstudios.com
13
 */
14
class CMB2_REST_Access extends CMB2_Hookup_Base {
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...
15
16
	/**
17
	 * @var   CMB2[] objects
18
	 * @since 2.2.0
19
	 */
20
	protected static $boxes;
21
22
	/**
23
	 * Whether metabox fields can be read via REST API
24
	 * @var   bool
25
	 * @since 2.2.0
26
	 */
27
	protected $can_read = true;
28
29
	/**
30
	 * Array of readable field objects.
31
	 * @var   CMB2_Field[]
32
	 * @since 2.2.0
33
	 */
34
	protected static $read_fields = array();
35
36
	/**
37
	 * Array of writeable field objects.
38
	 * @var   CMB2_Field[]
39
	 * @since 2.2.0
40
	 */
41
	protected static $write_fields = array();
42
43
	/**
44
	 * Whether metabox fields can be written via REST API
45
	 * @var   bool
46
	 * @since 2.2.0
47
	 */
48
	protected $can_write = false;
49
50
	public function __construct( CMB2 $cmb ) {
51
		$this->cmb = $cmb;
52
		self::$boxes[ $cmb->cmb_id ] = $cmb;
53
54
		$show_value = $this->cmb->prop( 'show_in_rest' );
55
		$this->cmb->rest_read  = 'write_only' !== $show_value;
0 ignored issues
show
Bug introduced by
The property rest_read does not seem to exist in CMB2.

An attempt at access to an undefined property has been detected. This may either be a typographical error or the property has been renamed but there are still references to its old name.

If you really want to allow access to undefined properties, you can define magic methods to allow access. See the php core documentation on Overloading.

Loading history...
56
		$this->cmb->rest_write = in_array( $show_value, array( 'read_and_write', 'write_only' ), true );
0 ignored issues
show
Bug introduced by
The property rest_write does not seem to exist in CMB2.

An attempt at access to an undefined property has been detected. This may either be a typographical error or the property has been renamed but there are still references to its old name.

If you really want to allow access to undefined properties, you can define magic methods to allow access. See the php core documentation on Overloading.

Loading history...
57
	}
58
59
	public function universal_hooks() {
60
		$this->once( 'rest_api_init', array( __CLASS__, 'register_fields' ), 50 );
61
62
		// hook up the CMB rest endpoint class
63
		$this->once( 'rest_api_init', array( cmb2_rest_endpoints(), 'register_routes' ), 0 );
64
65
		$this->prepare_read_write_fields();
66
67
		add_filter( 'is_protected_meta', array( $this, 'is_protected_meta' ), 10, 3 );
68
	}
69
70
	public static function register_fields() {
71
72
		$types = array();
73
		foreach ( self::$boxes as $cmb_id => $cmb ) {
74
			$types = array_merge( $types, $cmb->prop( 'object_types' ) );
75
		}
76
		$types = array_unique( $types );
77
78
		register_api_field(
79
			$types,
80
			'cmb2',
81
			array(
82
				'get_callback' => array( __CLASS__, 'get_restable_field_values' ),
83
				'update_callback' => array( __CLASS__, 'update_restable_field_values' ),
84
				'schema' => null,
85
			)
86
		);
87
	}
88
89
	protected function prepare_read_write_fields() {
90
		foreach ( $this->cmb->prop( 'fields' ) as $field ) {
91
			$show_in_rest = isset( $field['show_in_rest'] ) ? $field['show_in_rest'] : null;
92
93
			if ( false === $show_in_rest ) {
94
				continue;
95
			}
96
97
			$this->maybe_add_read_field( $field['id'], $show_in_rest );
98
			$this->maybe_add_write_field( $field['id'], $show_in_rest );
99
		}
100
	}
101
102 View Code Duplication
	protected function maybe_add_read_field( $field_id, $show_in_rest ) {
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...
103
		$can_read = $this->cmb->rest_read
0 ignored issues
show
Documentation introduced by
The property rest_read does not exist on object<CMB2>. 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...
104
			? 'write_only' !== $show_in_rest
105
			: in_array( $show_in_rest, array( 'read_and_write', 'read_only' ), true );
106
107
		if ( $can_read ) {
108
			self::$read_fields[ $this->cmb->cmb_id ][] = $field_id;
109
		}
110
	}
111
112 View Code Duplication
	protected function maybe_add_write_field( $field_id, $show_in_rest ) {
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...
113
		$can_update = $this->cmb->rest_write
0 ignored issues
show
Documentation introduced by
The property rest_write does not exist on object<CMB2>. 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...
114
			? 'read_only' !== $show_in_rest
115
			: in_array( $show_in_rest, array( 'read_and_write', 'write_only' ), true );
116
117
		if ( $can_update ) {
118
			self::$write_fields[ $this->cmb->cmb_id ][] = $field_id;
119
		}
120
	}
121
122
	/**
123
	 * Handler for getting custom field data.
124
	 * @since  2.2.0
125
	 * @param  array           $object   The object from the response
126
	 * @param  string          $field_id Name of field
127
	 * @param  WP_REST_Request $request  Current request
128
	 * @return mixed
129
	 */
130
	public static function get_restable_field_values( $object, $field_id, $request ) {
0 ignored issues
show
Unused Code introduced by
The parameter $field_id 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...
Unused Code introduced by
The parameter $request 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...
131
		$values = array();
132
		if ( ! isset( $object['id'] ) ) {
133
			return;
134
		}
135
136
		foreach ( self::$read_fields as $cmb_id => $fields ) {
137
			foreach ( $fields as $field_id ) {
0 ignored issues
show
Bug introduced by
The expression $fields of type object<CMB2_Field> is not traversable.
Loading history...
138
				$field = self::$boxes[ $cmb_id ]->get_field( $field_id );
139
				$field->object_id = $object['id'];
140
141
				if ( isset( $object->type ) ) {
142
					$field->object_type = $object->type;
143
				}
144
145
				$values[ $cmb_id ][ $field->id( true ) ] = $field->get_data();
146
			}
147
		}
148
149
		return $values;
150
	}
151
152
	/**
153
	 * Handler for updating custom field data.
154
	 * @since  2.2.0
155
	 * @param  mixed    $value    The value of the field
0 ignored issues
show
Documentation introduced by
There is no parameter named $value. Did you maybe mean $values?

This check looks for PHPDoc comments describing methods or function parameters that do not exist on the corresponding method or function. It has, however, found a similar but not annotated parameter which might be a good fit.

Consider the following example. The parameter $ireland is not defined by the method finale(...).

/**
 * @param array $germany
 * @param array $ireland
 */
function finale($germany, $island) {
    return "2:1";
}

The most likely cause is that the parameter was changed, but the annotation was not.

Loading history...
156
	 * @param  object   $object   The object from the response
157
	 * @param  string   $field_id Name of field
158
	 * @return bool|int
159
	 */
160
	public static function update_restable_field_values( $values, $object, $field_id ) {
161
		if ( empty( $values ) || ! is_array( $values ) || 'cmb2' !== $field_id ) {
162
			return;
163
		}
164
165
		$data = self::get_object_data( $object );
166
		if ( ! $data ) {
167
			return;
168
		}
169
170
		$object_id   = $data['object_id'];
171
		$object_type = $data['object_type'];
172
		$updated     = array();
173
174
		foreach ( self::$write_fields as $cmb_id => $fields ) {
175
			if ( ! array_key_exists( $cmb_id, $values ) ) {
176
				continue;
177
			}
178
179
			$cmb = self::$boxes[ $cmb_id ];
180
181
			$cmb->object_type( $object_id );
182
			$cmb->object_type( $object_type );
183
184
			$cmb->pre_process();
185
186
			foreach ( $fields as $field_id ) {
187
				if ( ! array_key_exists( $field_id, $values[ $cmb_id ] ) ) {
188
					continue;
189
				}
190
191
				$field = $cmb->get_field( $field_id );
192
193
				if ( 'title' == $field->type() ) {
194
					continue;
195
				}
196
197
				$field->object_id   = $object_id;
198
				$field->object_type = $object_type;
199
200
				if ( 'group' == $field->type() ) {
201
					$fields = $field->fields();
202
					if ( empty( $fields ) ) {
203
						continue;
204
					}
205
206
					$cmb->data_to_save[ $field_id ] = $values[ $cmb_id ][ $field_id ];
207
					$updated[ $cmb_id ][ $field_id ] = $cmb->save_group_field( $field );
0 ignored issues
show
Documentation introduced by
$field is of type object<CMB2_Field>|false, but the function expects a array.

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...
208
209
				} else {
210
					$updated[ $cmb_id ][ $field_id ] = $field->save_field( $values[ $cmb_id ][ $field_id ] );
211
				}
212
213
			}
214
215
			$cmb->after_save();
216
		}
217
218
		return $updated;
219
	}
220
221
	/**
222
	 * Filter whether a meta key is protected.
223
	 * @since 2.2.0
224
	 * @param bool   $protected Whether the key is protected. Default false.
225
	 * @param string $meta_key  Meta key.
226
	 * @param string $meta_type Meta type.
227
	 */
228
	public function is_protected_meta( $protected, $meta_key, $meta_type ) {
0 ignored issues
show
Unused Code introduced by
The parameter $meta_type 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...
229
		if ( $this->field_can_update( $meta_key ) ) {
230
			return false;
231
		}
232
233
		return $protected;
234
	}
235
236
	public function field_can_update( $field_id ) {
237
238
		$field        = $this->cmb->get_field( $field_id );
239
		$show_in_rest = $field ? $field->args( 'show_in_rest' ) : 'no';
240
		$can_update   = $this->cmb->rest_write
0 ignored issues
show
Documentation introduced by
The property rest_write does not exist on object<CMB2>. 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...
241
			? 'read_only' !== $show_in_rest
242
			: in_array( $show_in_rest, array( 'read_and_write', 'write_only' ), true );
243
244
		return $can_update ? $field : false;
245
	}
246
247
	protected static function get_object_data( $object ) {
248
		$object_id = 0;
249
		if ( isset( $object->ID ) ) {
250
			$object_id   = intval( $object->ID );
251
			$object_type = isset( $object->user_login ) ? 'user' : 'post';
252
		} elseif ( isset( $object->comment_ID ) ) {
253
			$object_id   = intval( $object->comment_ID );
254
			$object_type = 'comment';
255
		} elseif ( is_array( $object ) && isset( $object['term_id'] ) ) {
256
			$object_id   = intval( $object['term_id'] );
257
			$object_type = 'term';
258
		} elseif ( isset( $object->term_id ) ) {
259
			$object_id   = intval( $object->term_id );
260
			$object_type = 'term';
261
		}
262
263
		if ( empty( $object_id ) ) {
264
			return false;
265
		}
266
267
		return compact( 'object_id', 'object_type' );
268
	}
269
270
}
271