Skip to content

Instantly share code, notes, and snippets.

@rmccue
Created January 18, 2016 08:03
Show Gist options
  • Save rmccue/184a2329a922f6b4350d to your computer and use it in GitHub Desktop.
Save rmccue/184a2329a922f6b4350d to your computer and use it in GitHub Desktop.
<?php
/**
* Plugin Name: WP REST API Strict Mode
* Description: Triggers an error when unregistered parameters are used.
* Author: Ryan McCue
* Author URI: http://rmccue.io/
* Version: 0.1
*
* Requires https://core.trac.wordpress.org/ticket/35507
*/
add_action( 'rest_api_init', function () {
class Strict_REST_Request extends WP_REST_Request {
public function get_param( $key ) {
// Check the param is registered
$attributes = $this->get_attributes();
$args = isset( $attributes['args'] ) ? $attributes['args'] : array();
if ( ! isset( $args[ $key ] ) ) {
_doing_it_wrong(
'WP_REST_Request::get_param',
sprintf( 'Accessed unregistered parameter "%s"', $key ),
''
);
// Send a bonus header too.
header( sprintf( 'X-WP-Unregistered-Parameter: %s', $key ), false );
} elseif ( ! isset( $args[ $key ]['validate_callback'] ) && ! isset( $args[ $key ]['sanitize_callback'] ) ) {
_doing_it_wrong(
'WP_REST_Request::get_param',
sprintf( 'Registered parameter "%s" missing validation and sanitization', $key ),
''
);
// Send a bonus header too.
header( sprintf( 'X-WP-Parameter-No-Callback: %s', $key ), false );
}
return parent::get_param( $key );
}
}
});
add_filter( 'rest_dispatch_request', function ( $dispatch_result, $orig_request, $route, $handler ) {
// Pass-through existing overridden result.
if ( $dispatch_result !== null ) {
return $dispatch_result;
}
// Copy the request data into our wrapper object.
$request = new Strict_REST_Request(
$orig_request->get_method(),
$orig_request->get_route(),
$orig_request->get_attributes()
);
$request->set_url_params( $orig_request->get_url_params() );
$request->set_query_params( $orig_request->get_query_params() );
$request->set_body_params( $orig_request->get_body_params() );
$request->set_file_params( $orig_request->get_file_params() );
$request->set_default_params( $orig_request->get_default_params() );
$request->set_body( $orig_request->get_body() );
return call_user_func( $handler['callback'], $request );
}, 100, 4 );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment