Completed
Push — master ( 9c2b09...5e7564 )
by Francis
01:33
created

libraries/RESTResponse.php (2 issues)

1
<?php
2
defined('BASEPATH') OR exit('No direct script access allowed');
3
4
class RESTResponse extends CI_Controller
5
{
6
  // Response Codes
7
  // 40*
8
  const BAD_REQUEST           = 400;
9
  const UN_AUTHORIZED         = 401;
10
  const FORBIDDEN             = 403;
11
  const NOT_ACCEPTABLE        = 406;
12
  const TOO_MANY_REQUESTS     = 429;
13
  // 50*
14
  const INTERNAL_SERVER_ERROR = 500;
15
  const NOT_IMPLEMENTED       = 501;
16
  /**
17
   * [protected HTTP Response Code]
18
   * @var int
19
   */
20
  protected $code;
21
  /**
22
   * [protected Response Data]
23
   * @var mixed
24
   */
25
  protected $data;
26
  /**
27
   * [protected Shoud Response be JSON Encoded?]
28
   * @var bool
29
   */
30
  protected $json;
31
  function __construct($data=null, int $code=null)
32
  {
33
    $this->data = $data;
34
    $this->code = $code;
35
  }
36
  /**
37
   * [__toString description]
38
   * @date   2019-11-09
39
   * @return string     [description]
40
   */
41
  public function __toString():string
42
  {
43
    return !$this->json ? $this->data : n_encode($this->data);
44
  }
45
  /**
46
   * [json description]
47
   * @date   2019-11-11
48
   * @param  [type]       $data [description]
49
   * @param  int          $code [description]
50
   * @return RESTResponse       [description]
51
   */
52
  public function json($data, int $code):RESTResponse
53
  {
54
    $this->json = true;
55
    $this->code = $code;
56
    $this->data = $data;
57
    return $this;
58
  }
59
  /**
60
   * [send description]
61
   * @date  2019-11-11
62
   * @param boolean    $exit [description]
63
   */
64
  public function send(bool $exit=false):void
65
  {
66
    http_response_code($this->code ?? 200);
67
68
    if ($this->json) header('Content-Type: application/json');
69
70
    if ($this->data !== null) echo !$this->json ? $this->data : json_encode($this->data, JSON_PRETTY_PRINT|JSON_UNESCAPED_SLASHES);
71
72
    if ($exit) exit(EXIT_SUCCESS);
0 ignored issues
show
The constant EXIT_SUCCESS was not found. Maybe you did not declare it correctly or list all dependencies?
Loading history...
Using exit here is not recommended.

In general, usage of exit should be done with care and only when running in a scripting context like a CLI script.

Loading history...
73
  }
74
}
75
?>
76