Last active
May 15, 2018 07:52
-
-
Save hurlatunde/bc445c4b466779b0458160bd7c91d3b9 to your computer and use it in GitHub Desktop.
beforeFilter
This file contains hidden or 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 | |
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); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment