401 ) ); } if ( ! current_user_can( $capability ) ) { return new \WP_Error( 'slugh_rest_forbidden', __( 'You do not have permission to do this.', 'slugh' ), array( 'status' => 403 ) ); } return true; }; } /** * Read a request parameter that must be a single piece of text. An array or object gives an empty string. * * @param \WP_REST_Request $request Request. * @param string $key Parameter name. * @return string */ protected function text_param( \WP_REST_Request $request, $key ) { $value = $request->get_param( $key ); return is_scalar( $value ) ? (string) $value : ''; } /** * Register a route. * * @param string $route Route. * @param string $methods Methods. * @param callable $callback Callback. * @param string $capability Capability. * @param array $args Args schema. * @return void */ protected function route( $route, $methods, $callback, $capability, array $args = array() ) { register_rest_route( self::REST_NAMESPACE, $route, array( 'methods' => $methods, 'callback' => $callback, 'permission_callback' => $this->require_cap( $capability ), 'args' => $args, ) ); } /** * Convert a result that may be a WP_Error into a response, defaulting errors to HTTP 400. * * @param mixed $result Result. * @return \WP_REST_Response|\WP_Error */ protected function respond( $result ) { if ( is_wp_error( $result ) ) { $data = $result->get_error_data(); if ( ! is_array( $data ) || empty( $data['status'] ) ) { $result->add_data( array_merge( is_array( $data ) ? $data : array(), array( 'status' => 400 ) ) ); } return $result; } return rest_ensure_response( $result ); } }