Issues (71)

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
  /**
18
   * [protected HTTP Response Code]
19
   * @var int
20
   */
21
  protected $code;
22
23
  /**
24
   * [protected Response Data]
25
   * @var mixed
26
   */
27
  protected $data;
28
29
  /**
30
   * [protected Shoud Response be JSON Encoded?]
31
   * @var bool
32
   */
33
  protected $json;
34
35
  /**
36
   * [__construct description]
37
   * @date  2020-04-11
38
   * @param [type]     $data [description]
0 ignored issues
show
Documentation Bug introduced by
The doc comment [type] at position 0 could not be parsed: Unknown type name '[' at position 0 in [type].
Loading history...
39
   * @param integer    $code [description]
40
   */
41
  public function __construct($data=null, ?int $code=null)
42
  {
43
    $this->data = $data;
44
    $this->code = $code;
45
  }
46
47
  /**
48
   * [__toString description]
49
   * @date   2019-11-09
50
   * @return string     [description]
51
   */
52
  public function __toString():string
53
  {
54
    return !$this->json ? $this->data : json_encode($this->data);
55
  }
56
57
  /**
58
   * [json description]
59
   * @date   2019-11-11
60
   * @param  [type]       $data [description]
0 ignored issues
show
Documentation Bug introduced by
The doc comment [type] at position 0 could not be parsed: Unknown type name '[' at position 0 in [type].
Loading history...
61
   * @param  int          $code [description]
62
   * @return RESTResponse       [description]
63
   */
64
  public function json($data, ?int $code=null):RESTResponse
65
  {
66
    $this->json = true;
67
    $this->code = $code;
68
    $this->data = $data;
69
    return $this;
70
  }
71
72
  /**
73
   * [send description]
74
   * @date  2019-11-11
75
   * @param boolean    $exit [description]
76
   */
77
  public function send(bool $exit=false):void
78
  {
79
    http_response_code($this->code ?? 200);
80
81
    if ($this->json) header('Content-Type: application/json');
82
83
    if ($this->data !== null) echo !$this->json ? $this->data : json_encode($this->data, JSON_PRETTY_PRINT|JSON_UNESCAPED_SLASHES);
84
85
    if ($exit) exit(EXIT_SUCCESS);
86
  }
87
}
88
?>
89