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
$json_answer = json_encode($answer, JSON_UNESCAPED_UNICODE);
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
95
96
97
98
99
100
101
102
103
104
105
106
107
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;
}
}