Guest User

Untitled

a guest
May 20th, 2018
147
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.23 KB | None | 0 0
  1. <?php
  2.  
  3. class ApiController extends AppController {
  4.  
  5. const ERR_ERROR = 200;
  6. const ERR_BUNDLE_ERROR = 201;
  7. const ERR_FORM_VALIDATION_ERROR = 301;
  8. const ERR_DUPLICATE = 100;
  9. const ERR_EMPTY_DATA = 400;
  10.  
  11.  
  12. function beforeFilter() {
  13. parent::beforeFilter();
  14.  
  15. $this->response->header(array(
  16. 'Access-Control-Allow-Origin' => '*',
  17. 'Access-Control-Allow-Headers' => 'Content-Type'
  18. )
  19. );
  20. $this->autoRender = false;
  21. $this->FormValidatorApi->useModel = 'Data';
  22.  
  23. if ($_SERVER['REQUEST_METHOD'] == 'POST' && empty($_POST)){
  24. $_POST = array('Data'=>(array) json_decode(trim(file_get_contents('php://input')), true));
  25. }
  26.  
  27. if (!empty($_POST)){
  28. if(array_key_exists('postdata', $_POST) && $_POST['postdata']){
  29. $_POST = json_decode(trim($_POST['postdata']), true);
  30. }
  31. $this->request->data = array('Data' => $_POST);
  32. }
  33.  
  34. if (!empty($_POST) && !$this->request->data) {
  35. $this->request->data = $_POST;
  36. }
  37.  
  38. if ($this->request->data && !isset($this->request->data['Data'])) {
  39. $this->request->data = array('Data' => $this->request->data);
  40. }
  41. }
  42.  
  43.  
  44. function _throwError($error) {
  45. $this->_setResponse(compact('error'));
  46. }
  47.  
  48. function _setErrorResponse($errors, $errorCode, $result = array()) {
  49. $result = array_merge($result, array(
  50. 'success' => false,
  51. 'message' => "{$errors}",
  52. 'error_code' => $errorCode
  53. )
  54. );
  55. $this->_setResponse($result);
  56. }
  57.  
  58. function _setResponse($result = array()) {
  59. if (is_array($result) && !array_key_exists('success', $result)) {
  60. $result['success'] = true;
  61. if (!array_key_exists('message', $result)) {
  62. $result['message'] = "Successful";
  63. }
  64. }
  65.  
  66. if (!headers_sent()) {
  67. header('Content-Type: application/json');
  68. }
  69.  
  70. $result['action'] = $this->action;
  71. echo json_encode($result, JSON_PRETTY_PRINT);
  72. exit;
  73. }
  74.  
  75.  
  76. function index() {
  77. $error = 'There is nothing here';
  78. $this->_throwError($error);
  79. }
  80.  
  81. }
Add Comment
Please, Sign In to add comment