Last active
August 29, 2015 14:01
-
-
Save westonruter/b575f2951fd5d9dcfe8b to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
abstract class WP_Ajax_Action { | |
public $nopriv = true; | |
public $capability = 'read'; | |
public $name = ''; | |
public $nonce_check = true; | |
public $nonce_param = 'nonce'; | |
public $cache_max_age = 0; | |
public $allowed_request_methods = array( 'POST', 'GET' ); | |
public $frame_options = 'SAMEORIGIN'; | |
function __construct( $name, $args ) { | |
$this->name = $name; | |
$args = wp_parse_args( $args, get_object_vars( $this ) ); | |
foreach ( $args as $key => $value ) { | |
$this->$key = $value; | |
} | |
add_action( 'wp_ajax_' . $this->name, array( $this->_handle_priv_response ) ); | |
if ( $this->nopriv ) { | |
add_action( 'wp_ajax_nopriv_' . $this->name, array( $this->_handle_nopriv_response ) ); | |
} | |
} | |
function get_nonce() { | |
return wp_create_nonce( 'wp_ajax_' . $this->name ); | |
} | |
function _handle_nopriv_request() { | |
$this->_handle_request( array( 'nopriv' => true ) ); | |
} | |
function _handle_priv_request() { | |
$this->_handle_request( array( 'nopriv' => false ) ); | |
} | |
function _handle_request( $args = array() ) { | |
if ( ! $args['nopriv'] && ! current_user_can( $this->capability ) ) { | |
throw new WP_Ajax_Exception( 'forbidden' ); | |
} | |
if ( $this->nonce_check ) { | |
} | |
if ( $this->cache_max_age ) { | |
// @todo remove nocache headers | |
// @todo send Cache-Control max-age header | |
} | |
header( sprintf( 'X-Frame-Options: %s', $this->frame_options ) ); | |
try { | |
$data = $this->respond(); | |
wp_send_json_success( $data ); | |
} catch ( Exception $e ) { | |
$code = 500; | |
$data = 'Internal Server Error'; | |
if ( $e instanceof WP_Ajax_Exception ) { | |
$data = $e->data; | |
if ( $e->getCode() >= 400 && $e->getCode() < 600 ) { | |
$code = $e->getCode(); | |
} | |
} else if ( defined( 'WP_DEBUG' ) && WP_DEBUG ) { | |
$data = $e->getMessage(); | |
} | |
status_header( $code ); | |
wp_send_json_error( $data ); | |
} | |
} | |
/** | |
* @throws WP_Ajax_Exception | |
* @return data | |
*/ | |
abstract function respond(); | |
} | |
class WP_Ajax_Exception extends Exception { | |
public $data; | |
function __construct( $data, $status_code = 500, $status_text = 'Internal Server Error' ) { | |
$this->data = $data; | |
parent::__construct( $status_text, $status_code ); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment