Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <?php
- class ApiController extends AppController {
- const ERR_ERROR = 200;
- const ERR_BUNDLE_ERROR = 201;
- const ERR_FORM_VALIDATION_ERROR = 301;
- const ERR_DUPLICATE = 100;
- const ERR_EMPTY_DATA = 400;
- function beforeFilter() {
- parent::beforeFilter();
- $this->response->header(array(
- 'Access-Control-Allow-Origin' => '*',
- 'Access-Control-Allow-Headers' => 'Content-Type'
- )
- );
- $this->autoRender = false;
- $this->FormValidatorApi->useModel = 'Data';
- if ($_SERVER['REQUEST_METHOD'] == 'POST' && empty($_POST)){
- $_POST = array('Data'=>(array) json_decode(trim(file_get_contents('php://input')), true));
- }
- if (!empty($_POST)){
- if(array_key_exists('postdata', $_POST) && $_POST['postdata']){
- $_POST = json_decode(trim($_POST['postdata']), true);
- }
- $this->request->data = array('Data' => $_POST);
- }
- if (!empty($_POST) && !$this->request->data) {
- $this->request->data = $_POST;
- }
- if ($this->request->data && !isset($this->request->data['Data'])) {
- $this->request->data = array('Data' => $this->request->data);
- }
- }
- function _throwError($error) {
- $this->_setResponse(compact('error'));
- }
- function _setErrorResponse($errors, $errorCode, $result = array()) {
- $result = array_merge($result, array(
- 'success' => false,
- 'message' => "{$errors}",
- 'error_code' => $errorCode
- )
- );
- $this->_setResponse($result);
- }
- function _setResponse($result = array()) {
- if (is_array($result) && !array_key_exists('success', $result)) {
- $result['success'] = true;
- if (!array_key_exists('message', $result)) {
- $result['message'] = "Successful";
- }
- }
- if (!headers_sent()) {
- header('Content-Type: application/json');
- }
- $result['action'] = $this->action;
- echo json_encode($result, JSON_PRETTY_PRINT);
- exit;
- }
- function index() {
- $error = 'There is nothing here';
- $this->_throwError($error);
- }
- }
Add Comment
Please, Sign In to add comment