Completed
Push — master ( d7b630...7236b1 )
by Stefano
02:37
created

Request::host()   C

Complexity

Conditions 13
Paths 1280

Size

Total Lines 16
Code Lines 14

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 13
eloc 14
nc 1280
nop 1
dl 0
loc 16
rs 5.2936
c 0
b 0
f 0

How to fix   Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
3
/**
4
 * Request
5
 *
6
 * Handles the HTTP request for the current execution.
7
 *
8
 * @package core
9
 * @author [email protected]
10
 * @copyright Caffeina srl - 2016 - http://caffeina.com
11
 */
12
13
class Request {
14
  use Module;
15
16
  protected static $body,
0 ignored issues
show
Coding Style introduced by
It is generally advisable to only define one property per statement.

Only declaring a single property per statement allows you to later on add doc comments more easily.

It is also recommended by PSR2, so it is a common style that many people expect.

Loading history...
17
                   $accepts;
18
19
  /**
20
   * Handle Content Negotiation requests
21
   *
22
   * @param  string $key The name of the negotiation subject
23
   * @param  string $choices A query string for the negotiation choices (See RFC 7231)
24
   *
25
   * @return Object The preferred content if $choices is empty else return best match
26
   */
27
  public static function accept($key='type',$choices='') {
28
    if (null === static::$accepts) static::$accepts = [
29
      'type'     => new Negotiation(isset($_SERVER['HTTP_ACCEPT'])          ? $_SERVER['HTTP_ACCEPT']          : ''),
30
      'language' => new Negotiation(isset($_SERVER['HTTP_ACCEPT_LANGUAGE']) ? $_SERVER['HTTP_ACCEPT_LANGUAGE'] : ''),
31
      'encoding' => new Negotiation(isset($_SERVER['HTTP_ACCEPT_ENCODING']) ? $_SERVER['HTTP_ACCEPT_ENCODING'] : ''),
32
      'charset'  => new Negotiation(isset($_SERVER['HTTP_ACCEPT_CHARSET'])  ? $_SERVER['HTTP_ACCEPT_CHARSET']  : ''),
33
    ];
34
    return empty(static::$accepts[$key])
35
      ? false
36
      : ( empty($choices)
37
           ? static::$accepts[$key]->preferred()
38
           : static::$accepts[$key]->best($choices)
39
      );
40
  }
41
42
  /**
43
   * Retrive a value from generic input (from the $_REQUEST array)
44
   * Returns all elements if you pass `null` as $key
45
   *
46
   * @param  string $key The name of the input value
47
   *
48
   * @return Object The returned value or $default.
49
   */
50
  public static function input($key=null,$default=null){
51
    return $key ? (isset($_REQUEST[$key]) ? new Object($_REQUEST[$key]) : (is_callable($default)?call_user_func($default):$default))  : new Object($_REQUEST[$key]);
52
  }
53
54
  /**
55
   * Retrive a value from environment (from the $_ENV array)
56
   * Returns all elements if you pass `null` as $key
57
   *
58
   * @param  string $key The name of the input value
59
   *
60
   * @return Object The returned value or $default.
61
   */
62
  public static function env($key=null,$default=null){
63
    return $key ? (filter_input(INPUT_ENV,$key) ?: (is_callable($default)?call_user_func($default):$default))  : $_ENV;
64
  }
65
66
  /**
67
   * Retrive a value from server (from the $_SERVER array)
68
   * Returns all elements if you pass `null` as $key
69
   *
70
   * @param  string $key The name of the input value
71
   *
72
   * @return Object The returned value or $default.
73
   */
74
  public static function server($key=null,$default=null){
75
    return $key ? (isset($_SERVER[$key]) ? $_SERVER[$key] : (is_callable($default)?call_user_func($default):$default)) : $_SERVER;
76
  }
77
78
  /**
79
   * Retrive a value from generic input (from the $_POST array)
80
   * Returns all elements if you pass `null` as $key
81
   *
82
   * @param  string $key The name of the input value
83
   *
84
   * @return Object The returned value or $default.
85
   */
86
  public static function post($key=null,$default=null){
87
    return $key ? (filter_input(INPUT_POST,$key) ?: (is_callable($default)?call_user_func($default):$default)) : $_POST;
88
  }
89
90
  /**
91
   * Retrive a value from generic input (from the $_GET array)
92
   * Returns all elements if you pass `null` as $key
93
   *
94
   * @param  string $key The name of the input value
95
   *
96
   * @return Object The returned value or $default.
97
   */
98
  public static function get($key=null,$default=null){
99
    return $key ? (filter_input(INPUT_GET,$key) ?: (is_callable($default)?call_user_func($default):$default)) : $_GET;
100
  }
101
102
  /**
103
   * Retrive uploaded file (from the $_FILES array)
104
   * Returns all uploaded files if you pass `null` as $key
105
   *
106
   * @param  string $key The name of the input value
107
   *
108
   * @return Object The returned value or $default.
109
   */
110
  public static function files($key=null,$default=null){
111
    return $key ? (isset($_FILES[$key]) ? $_FILES[$key] : (is_callable($default)?call_user_func($default):$default))  : $_FILES;
112
  }
113
114
  /**
115
   * Retrive cookie (from the $_COOKIE array)
116
   * Returns all cookies if you pass `null` as $key
117
   *
118
   * @param  string $key The name of the input value
119
   *
120
   * @return Object The returned value or $default.
121
   */
122
  public static function cookie($key=null,$default=null){
123
    return $key ? (filter_input(INPUT_COOKIE,$key) ?: (is_callable($default)?call_user_func($default):$default))  : $_COOKIE;
124
  }
125
126
  /**
127
   * Returns the current host and port (omitted if port 80), complete with protocol (pass `false` to omit).
128
   *
129
   * @return string
130
   */
131
  public static function host($protocol=true){
132
    switch(true){
133
      case !empty($_SERVER['HTTP_X_FORWARDED_HOST']) :
134
        $host = trim(substr(strrchr($_SERVER['HTTP_X_FORWARDED_HOST'],','),1));
135
      break;
136
      case isset($_SERVER['HOSTNAME'])     : $host = $_SERVER['HOSTNAME'];    break;
137
      case isset($_SERVER['SERVER_NAME'])  : $host = $_SERVER['SERVER_NAME']; break;
138
      case isset($_SERVER['HTTP_HOST'])    : $host = $_SERVER['HTTP_HOST'];   break;
139
      default                              : $host = 'localhost';             break;
140
    }
141
    $host = explode(':',$host,2);
142
    $port = isset($host[1]) ? (int)$host[1] : (isset($_SERVER['SERVER_PORT'])?$_SERVER['SERVER_PORT']:80);
143
    $host = $host[0] . (($port && $port != 80) ? ":$port" : '');
144
    if ($port == 80) $port = '';
0 ignored issues
show
Unused Code introduced by
$port is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
145
    return ($protocol ? 'http' . (!empty($_SERVER['HTTPS'])&&(strtolower($_SERVER['HTTPS'])!=='off')?'s':'') . '://' : '') . Filter::with('core.request.host',$host);
146
  }
147
148
  /**
149
   * Returns the current request URL, complete with host and protocol.
150
   *
151
   * @return string
152
   */
153
  public static function URL(){
154
    return static::host(true) . static::URI(false);
155
  }
156
157
  /**
158
   * Retrive header
159
   * Returns all headers if you pass `null` as $key
160
   *
161
   * @param  string $key The name of the input value
162
   *
163
   * @return Object The returned value or null.
164
   */
165
  public static function header($key=null,$default=null){
166
    $key = 'HTTP_'.strtr(strtoupper($key),'-','_');
167
    return $key ? (isset($_SERVER[$key])? $_SERVER[$key] : (is_callable($default)?call_user_func($default):$default)) : $_SERVER;
168
  }
169
170
  /**
171
   * Returns the current request URI.
172
   *
173
   * @param  boolean $relative If true, trim the URI relative to the application index.php script.
174
   *
175
   * @return string
176
   */
177
  public static function URI($relative=true){
178
    // On some web server configurations SCRIPT_NAME is not populated.
179
    $self = isset($_SERVER['SCRIPT_NAME']) ? $_SERVER['SCRIPT_NAME'] : $_SERVER['PHP_SELF'];
180
    // Search REQUEST_URI in $_SERVER
181
    switch(true){
182
      case isset($_SERVER['PATH_INFO']):      $serv_uri = $_SERVER['PATH_INFO']; break;
183
      case isset($_SERVER['ORIG_PATH_INFO']): $serv_uri = $_SERVER['ORIG_PATH_INFO']; break;
184
      case isset($_SERVER['REQUEST_URI']):    $serv_uri = $_SERVER['REQUEST_URI']; break;
185
      default:                                $serv_uri = '/'; break;
186
    }
187
    $uri = strtok($serv_uri,'?');
188
    $uri = ($uri == $self) ? '/' : $uri;
189
190
    // Add a filter here, for URL rewriting
191
    $uri = Filter::with('core.request.URI',$uri);
192
193
    $uri = rtrim($uri,'/');
194
195
    if ($relative){
196
      $base = rtrim(dirname($self),'/');
197
      $uri = str_replace($base,'',$uri);
198
    }
199
200
    return $uri ?: '/';
201
  }
202
203
  /**
204
   * Returns the current base URI (The front-controller directory)
205
   *
206
   * @return string
207
   */
208
  public static function baseURI(){
209
    return dirname(isset($_SERVER['SCRIPT_NAME']) ? $_SERVER['SCRIPT_NAME'] : $_SERVER['PHP_SELF']) ?: '/';
210
  }
211
212
  /**
213
   * Returns the HTTP Method
214
   *
215
   * @return string
216
   */
217
  public static function method(){
218
   return Filter::with('core.request.method',strtolower(isset($_SERVER['REQUEST_METHOD'])?$_SERVER['REQUEST_METHOD']:'get'));
219
  }
220
221
  /**
222
   * Returns the remote IP
223
   *
224
   * @return string
225
   */
226
  public static function IP(){
227
   return Filter::with('core.request.IP',strtolower(isset($_SERVER['REMOTE_ADDR'])?$_SERVER['REMOTE_ADDR']:''));
228
  }
229
230
  /**
231
   * Returns the remote UserAgent
232
   *
233
   * @return string
234
   */
235
  public static function UA(){
236
   return Filter::with('core.request.UA',strtolower(isset($_SERVER['HTTP_USER_AGENT'])?$_SERVER['HTTP_USER_AGENT']:''));
237
  }
238
239
240
  /**
241
   * Returns request body data, convert to object if content type is JSON
242
   * Gives you all request data if you pass `null` as $key
243
   *
244
   * @param  string $key The name of the key requested
245
   *
246
   * @return mixed The request body data
247
   */
248
  public static function data($key=null,$default=null){
249
    if (null===static::$body){
250
      $json = (false !== stripos(isset($_SERVER['HTTP_CONTENT_TYPE'])?$_SERVER['HTTP_CONTENT_TYPE']:'','json'))
251
           || (false !== stripos(isset($_SERVER['CONTENT_TYPE'])?$_SERVER['CONTENT_TYPE']:'','json'));
252
      if ($json) {
253
        static::$body = json_decode(file_get_contents("php://input"));
254
      } else {
255
       if (empty($_POST)) {
256
          static::$body = file_get_contents("php://input");
257
        } else {
258
          static::$body = (object)$_POST;
259
        }
260
      }
261
    }
262
    return $key ? (isset(static::$body->$key) ? static::$body->$key : (is_callable($default)?call_user_func($default):$default))  : static::$body;
263
  }
264
265
}
266