Hoa central
Runtime.php
Go to the documentation of this file.
1 <?php
2 
37 namespace Hoa\Http;
38 
47 class Runtime
48 {
54  public static function getMethod()
55  {
56  if ('cli' === php_sapi_name()) {
57  return 'get';
58  }
59 
60  return strtolower($_SERVER['REQUEST_METHOD']);
61  }
62 
68  public static function getUri()
69  {
70  return $_SERVER['REQUEST_URI'];
71  }
72 
80  public static function getData($extended = true)
81  {
82  switch (static::getMethod()) {
84  return $_GET;
85 
87  $contentType = static::getHeader('Content-Type');
88 
89  switch ($contentType) {
90  case 'application/x-www-form-urlencoded':
91  return $_POST;
92 
93  case 'application/json':
94  $input = file_get_contents('php://input');
95 
96  if (true !== $extended ||
97  true !== function_exists('json_decode')) {
98  return $input;
99  }
100 
101  $json = json_decode($input, true);
102 
103  if (JSON_ERROR_NONE !== json_last_error()) {
104  return $input;
105  }
106 
107  return $json;
108 
109  default:
110  return file_get_contents('php://input');
111  }
112 
113  break;
114 
115  case Request::METHOD_PUT:
117  return file_get_contents('php://input');
118 
119  default:
120  return null;
121  }
122  }
123 
129  public static function hasData()
130  {
131  if (Request::METHOD_GET === static::getMethod()) {
132  return !empty($_GET);
133  }
134 
135  return 0 < intval(static::getHeader('Content-Length'));
136  }
137 
143  public static function getHeaders()
144  {
145  static $_headers = [];
146 
147  if (!empty($_headers)) {
148  return $_headers;
149  }
150 
151  if (true === function_exists('apache_request_headers')) {
152  foreach (apache_request_headers() as $header => $value) {
153  $_headers[strtolower($header)] = $value;
154  }
155  } else {
156  if (isset($_SERVER['CONTENT_TYPE'])) {
157  $_headers['content-type'] = $_SERVER['CONTENT_TYPE'];
158  }
159 
160  if (isset($_SERVER['CONTENT_LENGTH'])) {
161  $_headers['content-length'] = $_SERVER['CONTENT_LENGTH'];
162  }
163 
164  foreach ($_SERVER as $key => $value) {
165  if ('HTTP_' === substr($key, 0, 5)) {
166  $_headers[strtolower(str_replace('_', '-', substr($key, 5)))]
167  = $value;
168  }
169  }
170  }
171 
172  return $_headers;
173  }
174 
181  public static function getHeader($header)
182  {
183  $headers = static::getHeaders();
184  $header = strtolower($header);
185 
186  if (true !== array_key_exists($header, $headers)) {
187  return null;
188  }
189 
190  return $headers[$header];
191  }
192 }
static getData($extended=true)
Definition: Runtime.php:80
const METHOD_PUT
Definition: Request.php:103
static getHeader($header)
Definition: Runtime.php:181
const METHOD_PATCH
Definition: Request.php:89
static getUri()
Definition: Runtime.php:68
static hasData()
Definition: Runtime.php:129
static getHeaders()
Definition: Runtime.php:143
const METHOD_POST
Definition: Request.php:96
const METHOD_GET
Definition: Request.php:68
static getMethod()
Definition: Runtime.php:54