Response.class.php 1.66 KB
Newer Older
Quentin Vrel's avatar
Quentin Vrel committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61
<?php
class Response {
   protected $code;
   protected $body;

   public function __construct($code = 404, $msg = "") {
      $this->code = $code;
      $this->body = $msg;
   }

   public static function errorResponse($message = "") {
      return new Response(400,$message);
   }

   public static function serverErrorResponse($message = "")
   {
      return new Response(500,$message);
   }

   public static function okResponse($message = "")
   {
      return new Response(200,$message);
   }

   public static function notFoundResponse($message = "")
   {
      return new Response(404,$message);
   }

   public static function errorInParametersResponse($message = "")
   {
      return new Response(400,$message);
   }

   public static function interceptEchos() {
      ob_start();
   }

   public static function getEchos() {
      return ob_get_clean();
   }

   public function send() {
      // https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Access-Control-Allow-Origin
      header("Access-Control-Allow-Origin: *");

      header("Content-Type: application/json; charset=UTF-8");

      // https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Access-Control-Allow-Methods
      header("Access-Control-Allow-Methods: GET,POST,PUT,DELETE");

      header("Access-Control-Max-Age: 3600"); // Maximum number of seconds the results can be cached.

      // https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Access-Control-Allow-Headers
      header("Access-Control-Allow-Headers: Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With");

      http_response_code($this->code);
      echo $this->body;
      exit; // do we keep that?
   }
}