Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP

Loading…

Add json_ensure_response #154

Merged
merged 1 commit into from

2 participants

@rmccue
Owner

This ensures that a value is either a WP_JSON_ResponseInterface object, or a WP_Error, by wrapping any other value in a WP_JSON_Response instance.

Fixes #151.

@rmccue rmccue Add json_ensure_response
This ensures that a value is either a WP_JSON_ResponseInterface object,
or a WP_Error, by wrapping any other value in a WP_JSON_Response
instance.
1c72d1c
@rmccue
Owner

@rachelbaker #reviewmerge

@rmccue rmccue added this to the 1.0 milestone
@rachelbaker rachelbaker modified the milestone: 1.0
@rachelbaker rachelbaker merged commit c0f8ae3 into from
@rachelbaker rachelbaker deleted the branch
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Commits on Apr 29, 2014
  1. @rmccue

    Add json_ensure_response

    rmccue authored
    This ensures that a value is either a WP_JSON_ResponseInterface object,
    or a WP_Error, by wrapping any other value in a WP_JSON_Response
    instance.
This page is out of date. Refresh to see the latest.
Showing with 25 additions and 1 deletion.
  1. +1 −1  lib/class-wp-json-posts.php
  2. +24 −0 plugin.php
View
2  lib/class-wp-json-posts.php
@@ -218,7 +218,7 @@ function new_post( $data ) {
return $result;
}
- $response = $this->get_post( $result );
+ $response = json_ensure_response( $this->get_post( $result ) );
$response->set_status( 201 );
$response->header( 'Location', json_url( '/posts/' . $result ) );
return $response;
View
24 plugin.php
@@ -286,3 +286,27 @@ function get_json_url( $blog_id = null, $path = '', $scheme = 'json' ) {
function json_url( $path = '', $scheme = 'json' ) {
return get_json_url( null, $path, $scheme );
}
+
+/**
+ * Ensure a JSON response is a response object
+ *
+ * This ensures that the response is consistent, and implements
+ * {@see WP_JSON_ResponseInterface}, allowing usage of
+ * `set_status`/`header`/etc without needing to double-check the object. Will
+ * also allow {@see WP_Error} to indicate error responses, so users should
+ * immediately check for this value.
+ *
+ * @param WP_Error|WP_JSON_ResponseInterface|mixed $response Response to check
+ * @return WP_Error|WP_JSON_ResponseInterface
+ */
+function json_ensure_response( $response ) {
+ if ( is_wp_error( $response ) ) {
+ return $response;
+ }
+
+ if ( $response instanceof WP_JSON_ResponseInterface ) {
+ return $response;
+ }
+
+ return new WP_JSON_Response( $response );
+}
Something went wrong with that request. Please try again.