AjaxController.php 2.07 KB
Newer Older
Pham Huy committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94
<?php
/**
 * 
 */
abstract class Loco_mvc_AjaxController extends Loco_mvc_Controller {
    
    /**
     * Request arguments injected from Router
     * @var ArrayObject
     */
    private $input;
    
    /**
     * Data to respond with as JSON
     * @var ArrayObject
     */
    private $output;


    /**
     * Pre-init call invoked by router
     * @return Loco_mvc_AjaxController
     */    
    final public function _init( array $args ){
        $this->auth();
        $this->output = new ArrayObject;
        $this->input = new ArrayObject( $args );
        // avoid fatal error if json extension is missing
        loco_check_extension('json');
    }


    /**
     * Get posted data and validate nonce in the process
     * @return Loco_mvc_PostParams
     */
    protected function validate(){
        $route = $this->input['route'];
        if( ! $this->checkNonce($route) ){
            throw new Loco_error_Exception( sprintf('Ajax %s action requires postdata with nonce',$route) );
        }
        return Loco_mvc_PostParams::get();
    }


    /**
     * {@inheritdoc}
     */
    public function get( $prop ){
        return isset($this->input[$prop]) ? $this->input[$prop] : null;
    }


    /**
     * {@inheritdoc}
     */
    public function set( $prop, $value ){
        $this->output[$prop] = $value;
        return $this;
    }



    /**
     * @return string JSON
     */
    public function render(){
        $data = array (
            'data' => $this->output->getArrayCopy(),
        );
        // non-fatal notices deliberately not in "error" key
        if( $array = Loco_error_AdminNotices::destroyAjax() ){
            $data['notices'] = $array;
        }
        return json_encode( $data );
    }



    /**
     * Pretty json encode if PHP version allows
     *
    protected function json_encode( $data ){
        $opts = 0;
        if( defined('JSON_PRETTY_PRINT') ){
            $opts |= JSON_PRETTY_PRINT;
        }
        if( defined('JSON_UNESCAPED_SLASHES') ){
            $opts |= JSON_UNESCAPED_SLASHES;
        }
        return json_encode( $data, $opts );
    }*/
    
}