Skip to content
Snippets Groups Projects
Handler.php 3.41 KiB
Newer Older
<?php defined('SYSPATH') OR die('No direct script access.');

abstract class Controller_Api_Handler extends Controller_Handler {

    public function before() {
        // todo: var $user should be defined here
        //    either by GET param (token),
        //    or on the session variables.
        $this->setAccessLevel(self::ACCESS_USER);
        parent::before();
    }

    public function execute()
    {
        // Execute the "before action" method
        $this->before();

        // Determine the action to use
        $action = 'action_' . $this->request->action();

        // If the action doesn't exist, it's a 404
        if (!method_exists($this, $action)) {
            throw HTTP_Exception::factory(404,
                'The requested URL :uri was not found on this server.',
                array(':uri' => $this->request->uri())
            )->request($this->request);
        }

        try {
            // Execute the action itself
            $data = $this->{$action}();
            $answer = ['response' => ($data ? $data : '')];
        } catch (LogicException $e) {
            $answer = ['error' => [
                'code'     => (int) $e->getCode(),
                'message'  => (string) $e->getMessage(),
//                'request'  => $this->request->params    // like http://vk.com/dev/captcha_error
            ]];
        }

        // Json API
xamgore's avatar
xamgore committed
        $json_answer = json_encode($answer, JSON_UNESCAPED_UNICODE);
        if (!$this->request->is_ajax())
            $json_answer = $this->indent($json_answer);
        $this->response->body($json_answer);

        // Execute the "after action" method
        $this->after();

        // Return the response
        return $this->response;
    }

    /**
     * Indents a flat JSON string to make it more human-readable.
     * @param string $json The original JSON string to process.
     * @return string Indented version of the original JSON string.
     */
    private function &indent(&$json) {
        $result      = '';
        $pos         = 0;
        $strLen      = strlen($json);
        $indentStr   = '  ';
        $newLine     = "\n";
        $prevChar    = '';
        $outOfQuotes = true;

        for ($i=0; $i<=$strLen; $i++) {
            // Grab the next character in the string.
            $char = substr($json, $i, 1);

            // Are we inside a quoted string?
            if ($char == '"' && $prevChar != '\\') {
                $outOfQuotes = !$outOfQuotes;

                // If this character is the end of an element,
                // output a new line and indent the next line.
            } else if(($char == '}' || $char == ']') && $outOfQuotes) {
                $result .= $newLine;
                $pos --;
                for ($j=0; $j<$pos; $j++) {
                    $result .= $indentStr;
                }
            }

            // Add the character to the result string.
            $result .= $char;

            // If the last character was the beginning of an element,
            // output a new line and indent the next line.
            if (($char == ',' || $char == '{' || $char == '[') && $outOfQuotes) {
                $result .= $newLine;
                if ($char == '{' || $char == '[') {
                    $pos ++;
                }

                for ($j = 0; $j < $pos; $j++) {
                    $result .= $indentStr;
                }
            }

            $prevChar = $char;
        }

        return $result;
    }
}