3 * REST API: WP_REST_Controller class
11 * Core base controller for managing and interacting with REST API items.
15 abstract class WP_REST_Controller {
18 * The namespace of this controller's route.
27 * The base of this controller's route.
36 * Registers the routes for the objects of the controller.
41 public function register_routes() {
42 _doing_it_wrong( 'WP_REST_Controller::register_routes', __( 'The register_routes() method must be overridden' ), '4.7' );
46 * Checks if a given request has access to get items.
51 * @param WP_REST_Request $request Full data about the request.
52 * @return WP_Error|bool True if the request has read access, WP_Error object otherwise.
54 public function get_items_permissions_check( $request ) {
55 return new WP_Error( 'invalid-method', sprintf( __( "Method '%s' not implemented. Must be overridden in subclass." ), __METHOD__ ), array( 'status' => 405 ) );
59 * Retrieves a collection of items.
64 * @param WP_REST_Request $request Full data about the request.
65 * @return WP_Error|WP_REST_Response Response object on success, or WP_Error object on failure.
67 public function get_items( $request ) {
68 return new WP_Error( 'invalid-method', sprintf( __( "Method '%s' not implemented. Must be overridden in subclass." ), __METHOD__ ), array( 'status' => 405 ) );
72 * Checks if a given request has access to get a specific item.
77 * @param WP_REST_Request $request Full data about the request.
78 * @return WP_Error|bool True if the request has read access for the item, WP_Error object otherwise.
80 public function get_item_permissions_check( $request ) {
81 return new WP_Error( 'invalid-method', sprintf( __( "Method '%s' not implemented. Must be overridden in subclass." ), __METHOD__ ), array( 'status' => 405 ) );
85 * Retrieves one item from the collection.
90 * @param WP_REST_Request $request Full data about the request.
91 * @return WP_Error|WP_REST_Response Response object on success, or WP_Error object on failure.
93 public function get_item( $request ) {
94 return new WP_Error( 'invalid-method', sprintf( __( "Method '%s' not implemented. Must be overridden in subclass." ), __METHOD__ ), array( 'status' => 405 ) );
98 * Checks if a given request has access to create items.
103 * @param WP_REST_Request $request Full data about the request.
104 * @return WP_Error|bool True if the request has access to create items, WP_Error object otherwise.
106 public function create_item_permissions_check( $request ) {
107 return new WP_Error( 'invalid-method', sprintf( __( "Method '%s' not implemented. Must be overridden in subclass." ), __METHOD__ ), array( 'status' => 405 ) );
111 * Creates one item from the collection.
116 * @param WP_REST_Request $request Full data about the request.
117 * @return WP_Error|WP_REST_Response Response object on success, or WP_Error object on failure.
119 public function create_item( $request ) {
120 return new WP_Error( 'invalid-method', sprintf( __( "Method '%s' not implemented. Must be overridden in subclass." ), __METHOD__ ), array( 'status' => 405 ) );
124 * Checks if a given request has access to update a specific item.
129 * @param WP_REST_Request $request Full data about the request.
130 * @return WP_Error|bool True if the request has access to update the item, WP_Error object otherwise.
132 public function update_item_permissions_check( $request ) {
133 return new WP_Error( 'invalid-method', sprintf( __( "Method '%s' not implemented. Must be overridden in subclass." ), __METHOD__ ), array( 'status' => 405 ) );
137 * Updates one item from the collection.
142 * @param WP_REST_Request $request Full data about the request.
143 * @return WP_Error|WP_REST_Response Response object on success, or WP_Error object on failure.
145 public function update_item( $request ) {
146 return new WP_Error( 'invalid-method', sprintf( __( "Method '%s' not implemented. Must be overridden in subclass." ), __METHOD__ ), array( 'status' => 405 ) );
150 * Checks if a given request has access to delete a specific item.
155 * @param WP_REST_Request $request Full data about the request.
156 * @return WP_Error|bool True if the request has access to delete the item, WP_Error object otherwise.
158 public function delete_item_permissions_check( $request ) {
159 return new WP_Error( 'invalid-method', sprintf( __( "Method '%s' not implemented. Must be overridden in subclass." ), __METHOD__ ), array( 'status' => 405 ) );
163 * Deletes one item from the collection.
168 * @param WP_REST_Request $request Full data about the request.
169 * @return WP_Error|WP_REST_Response Response object on success, or WP_Error object on failure.
171 public function delete_item( $request ) {
172 return new WP_Error( 'invalid-method', sprintf( __( "Method '%s' not implemented. Must be overridden in subclass." ), __METHOD__ ), array( 'status' => 405 ) );
176 * Prepares one item for create or update operation.
181 * @param WP_REST_Request $request Request object.
182 * @return WP_Error|object The prepared item, or WP_Error object on failure.
184 protected function prepare_item_for_database( $request ) {
185 return new WP_Error( 'invalid-method', sprintf( __( "Method '%s' not implemented. Must be overridden in subclass." ), __METHOD__ ), array( 'status' => 405 ) );
189 * Prepares the item for the REST response.
194 * @param mixed $item WordPress representation of the item.
195 * @param WP_REST_Request $request Request object.
196 * @return WP_Error|WP_REST_Response Response object on success, or WP_Error object on failure.
198 public function prepare_item_for_response( $item, $request ) {
199 return new WP_Error( 'invalid-method', sprintf( __( "Method '%s' not implemented. Must be overridden in subclass." ), __METHOD__ ), array( 'status' => 405 ) );
203 * Prepares a response for insertion into a collection.
208 * @param WP_REST_Response $response Response object.
209 * @return array|mixed Response data, ready for insertion into collection data.
211 public function prepare_response_for_collection( $response ) {
212 if ( ! ( $response instanceof WP_REST_Response ) ) {
216 $data = (array) $response->get_data();
217 $server = rest_get_server();
219 if ( method_exists( $server, 'get_compact_response_links' ) ) {
220 $links = call_user_func( array( $server, 'get_compact_response_links' ), $response );
222 $links = call_user_func( array( $server, 'get_response_links' ), $response );
225 if ( ! empty( $links ) ) {
226 $data['_links'] = $links;
233 * Filters a response based on the context defined in the schema.
238 * @param array $data Response data to fiter.
239 * @param string $context Context defined in the schema.
240 * @return array Filtered response.
242 public function filter_response_by_context( $data, $context ) {
244 $schema = $this->get_item_schema();
246 foreach ( $data as $key => $value ) {
247 if ( empty( $schema['properties'][ $key ] ) || empty( $schema['properties'][ $key ]['context'] ) ) {
251 if ( ! in_array( $context, $schema['properties'][ $key ]['context'], true ) ) {
252 unset( $data[ $key ] );
256 if ( 'object' === $schema['properties'][ $key ]['type'] && ! empty( $schema['properties'][ $key ]['properties'] ) ) {
257 foreach ( $schema['properties'][ $key ]['properties'] as $attribute => $details ) {
258 if ( empty( $details['context'] ) ) {
262 if ( ! in_array( $context, $details['context'], true ) ) {
263 if ( isset( $data[ $key ][ $attribute ] ) ) {
264 unset( $data[ $key ][ $attribute ] );
275 * Retrieves the item's schema, conforming to JSON Schema.
280 * @return array Item schema data.
282 public function get_item_schema() {
283 return $this->add_additional_fields_schema( array() );
287 * Retrieves the item's schema for display / public consumption purposes.
292 * @return array Public item schema data.
294 public function get_public_item_schema() {
296 $schema = $this->get_item_schema();
298 foreach ( $schema['properties'] as &$property ) {
299 unset( $property['arg_options'] );
306 * Retrieves the query params for the collections.
311 * @return array Query parameters for the collection.
313 public function get_collection_params() {
315 'context' => $this->get_context_param(),
317 'description' => __( 'Current page of the collection.' ),
320 'sanitize_callback' => 'absint',
321 'validate_callback' => 'rest_validate_request_arg',
325 'description' => __( 'Maximum number of items to be returned in result set.' ),
330 'sanitize_callback' => 'absint',
331 'validate_callback' => 'rest_validate_request_arg',
334 'description' => __( 'Limit results to those matching a string.' ),
336 'sanitize_callback' => 'sanitize_text_field',
337 'validate_callback' => 'rest_validate_request_arg',
343 * Retrieves the magical context param.
345 * Ensures consistent descriptions between endpoints, and populates enum from schema.
350 * @param array $args Optional. Additional arguments for context parameter. Default empty array.
351 * @return array Context parameter details.
353 public function get_context_param( $args = array() ) {
354 $param_details = array(
355 'description' => __( 'Scope under which the request is made; determines fields present in response.' ),
357 'sanitize_callback' => 'sanitize_key',
358 'validate_callback' => 'rest_validate_request_arg',
361 $schema = $this->get_item_schema();
363 if ( empty( $schema['properties'] ) ) {
364 return array_merge( $param_details, $args );
369 foreach ( $schema['properties'] as $attributes ) {
370 if ( ! empty( $attributes['context'] ) ) {
371 $contexts = array_merge( $contexts, $attributes['context'] );
375 if ( ! empty( $contexts ) ) {
376 $param_details['enum'] = array_unique( $contexts );
377 rsort( $param_details['enum'] );
380 return array_merge( $param_details, $args );
384 * Adds the values from additional fields to a data object.
389 * @param array $object Data object.
390 * @param WP_REST_Request $request Full details about the request.
391 * @return array Modified data object with additional fields.
393 protected function add_additional_fields_to_object( $object, $request ) {
395 $additional_fields = $this->get_additional_fields();
397 foreach ( $additional_fields as $field_name => $field_options ) {
399 if ( ! $field_options['get_callback'] ) {
403 $object[ $field_name ] = call_user_func( $field_options['get_callback'], $object, $field_name, $request, $this->get_object_type() );
410 * Updates the values of additional fields added to a data object.
415 * @param array $object Data Object.
416 * @param WP_REST_Request $request Full details about the request.
417 * @return bool|WP_Error True on success, WP_Error object if a field cannot be updated.
419 protected function update_additional_fields_for_object( $object, $request ) {
420 $additional_fields = $this->get_additional_fields();
422 foreach ( $additional_fields as $field_name => $field_options ) {
423 if ( ! $field_options['update_callback'] ) {
427 // Don't run the update callbacks if the data wasn't passed in the request.
428 if ( ! isset( $request[ $field_name ] ) ) {
432 $result = call_user_func( $field_options['update_callback'], $request[ $field_name ], $object, $field_name, $request, $this->get_object_type() );
434 if ( is_wp_error( $result ) ) {
443 * Adds the schema from additional fields to a schema array.
445 * The type of object is inferred from the passed schema.
450 * @param array $schema Schema array.
451 * @return array Modified Schema array.
453 protected function add_additional_fields_schema( $schema ) {
454 if ( empty( $schema['title'] ) ) {
458 // Can't use $this->get_object_type otherwise we cause an inf loop.
459 $object_type = $schema['title'];
461 $additional_fields = $this->get_additional_fields( $object_type );
463 foreach ( $additional_fields as $field_name => $field_options ) {
464 if ( ! $field_options['schema'] ) {
468 $schema['properties'][ $field_name ] = $field_options['schema'];
475 * Retrieves all of the registered additional fields for a given object-type.
480 * @param string $object_type Optional. The object type.
481 * @return array Registered additional fields (if any), empty array if none or if the object type could
484 protected function get_additional_fields( $object_type = null ) {
486 if ( ! $object_type ) {
487 $object_type = $this->get_object_type();
490 if ( ! $object_type ) {
494 global $wp_rest_additional_fields;
496 if ( ! $wp_rest_additional_fields || ! isset( $wp_rest_additional_fields[ $object_type ] ) ) {
500 return $wp_rest_additional_fields[ $object_type ];
504 * Retrieves the object type this controller is responsible for managing.
509 * @return string Object type for the controller.
511 protected function get_object_type() {
512 $schema = $this->get_item_schema();
514 if ( ! $schema || ! isset( $schema['title'] ) ) {
518 return $schema['title'];
522 * Retrieves an array of endpoint arguments from the item schema for the controller.
527 * @param string $method Optional. HTTP method of the request. The arguments for `CREATABLE` requests are
528 * checked for required values and may fall-back to a given default, this is not done
529 * on `EDITABLE` requests. Default WP_REST_Server::CREATABLE.
530 * @return array Endpoint arguments.
532 public function get_endpoint_args_for_item_schema( $method = WP_REST_Server::CREATABLE ) {
534 $schema = $this->get_item_schema();
535 $schema_properties = ! empty( $schema['properties'] ) ? $schema['properties'] : array();
536 $endpoint_args = array();
538 foreach ( $schema_properties as $field_id => $params ) {
540 // Arguments specified as `readonly` are not allowed to be set.
541 if ( ! empty( $params['readonly'] ) ) {
545 $endpoint_args[ $field_id ] = array(
546 'validate_callback' => 'rest_validate_request_arg',
547 'sanitize_callback' => 'rest_sanitize_request_arg',
550 if ( isset( $params['description'] ) ) {
551 $endpoint_args[ $field_id ]['description'] = $params['description'];
554 if ( WP_REST_Server::CREATABLE === $method && isset( $params['default'] ) ) {
555 $endpoint_args[ $field_id ]['default'] = $params['default'];
558 if ( WP_REST_Server::CREATABLE === $method && ! empty( $params['required'] ) ) {
559 $endpoint_args[ $field_id ]['required'] = true;
562 foreach ( array( 'type', 'format', 'enum', 'items' ) as $schema_prop ) {
563 if ( isset( $params[ $schema_prop ] ) ) {
564 $endpoint_args[ $field_id ][ $schema_prop ] = $params[ $schema_prop ];
568 // Merge in any options provided by the schema property.
569 if ( isset( $params['arg_options'] ) ) {
571 // Only use required / default from arg_options on CREATABLE endpoints.
572 if ( WP_REST_Server::CREATABLE !== $method ) {
573 $params['arg_options'] = array_diff_key( $params['arg_options'], array( 'required' => '', 'default' => '' ) );
576 $endpoint_args[ $field_id ] = array_merge( $endpoint_args[ $field_id ], $params['arg_options'] );
580 return $endpoint_args;
584 * Sanitizes the slug value.
589 * @internal We can't use sanitize_title() directly, as the second
590 * parameter is the fallback title, which would end up being set to the
593 * @see https://github.com/WP-API/WP-API/issues/1585
595 * @todo Remove this in favour of https://core.trac.wordpress.org/ticket/34659
597 * @param string $slug Slug value passed in request.
598 * @return string Sanitized value for the slug.
600 public function sanitize_slug( $slug ) {
601 return sanitize_title( $slug );