Request::data()   B
last analyzed

Complexity

Conditions 10
Paths 56

Size

Total Lines 16

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 10
nc 56
nop 2
dl 0
loc 16
rs 7.6666
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,
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 Structure The returned value or $default.
49
   */
50
  public static function input($key=null,$default=null){
51
    return $key ? (isset($_REQUEST[$key]) ? new Structure($_REQUEST[$key]) : (is_callable($default)?call_user_func($default):$default))  : new Structure($_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).
128
   *
129
   * @param bool $with_protocol Pass true to prepend protocol to hostname
130
   *
131
   * @return string
132
   */
133
  public static function host($with_protocol=true){
134
    switch(true){
135 View Code Duplication
      case !empty($_SERVER['HTTP_X_FORWARDED_HOST']) :
136
        $host = trim(substr(strrchr($_SERVER['HTTP_X_FORWARDED_HOST'],','),1) ?: $_SERVER['HTTP_X_FORWARDED_HOST']);
137
      break;
138
      case !empty($_SERVER['HTTP_HOST'])    : $host = $_SERVER['HTTP_HOST'];   break;
139
      case !empty($_SERVER['SERVER_NAME'])  : $host = $_SERVER['SERVER_NAME']; break;
140
      case !empty($_SERVER['HOSTNAME'])     : $host = $_SERVER['HOSTNAME'];    break;
141
      default                               : $host = 'localhost';             break;
142
    }
143
    $host = explode(':',$host,2);
144
    $port = isset($host[1]) ? (int)$host[1] : (isset($_SERVER['SERVER_PORT'])?$_SERVER['SERVER_PORT']:80);
145
    $host = $host[0] . (($port && $port != 80) ? ":$port" : '');
146
    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...
147
    return ($with_protocol ? 'http' . (!empty($_SERVER['HTTPS'])&&(strtolower($_SERVER['HTTPS'])!=='off')?'s':'') . '://' : '')
148
           . Filter::with('core.request.host',$host);
149
  }
150
151
  /**
152
   * Returns the current request URL, complete with host and protocol.
153
   *
154
   * @return string
155
   */
156
  public static function URL(){
157
    return static::host(true) . static::URI();
158
  }
159
160
  /**
161
   * Retrive header
162
   * Returns all headers if you pass `null` as $key
163
   *
164
   * @param  string $key The name of the input value
165
   *
166
   * @return Object The returned value or null.
167
   */
168
  public static function header($key=null,$default=null){
169
    if ($key) $key = 'HTTP_'.strtr(strtoupper($key),'-','_');
0 ignored issues
show
Bug Best Practice introduced by
The expression $key of type string|null is loosely compared to true; this is ambiguous if the string can be empty. You might want to explicitly use !== null instead.

In PHP, under loose comparison (like ==, or !=, or switch conditions), values of different types might be equal.

For string values, the empty string '' is a special case, in particular the following results might be unexpected:

''   == false // true
''   == null  // true
'ab' == false // false
'ab' == null  // false

// It is often better to use strict comparison
'' === false // false
'' === null  // false
Loading history...
170
    return $key ? (isset($_SERVER[$key])? $_SERVER[$key] : (is_callable($default)?call_user_func($default):$default)) : array_filter($_SERVER, function($k) {
171
       return strrpos($k, "HTTP_") === 0;
172
    }, ARRAY_FILTER_USE_KEY);
173
  }
174
175
  /**
176
   * Returns the current request URI.
177
   *
178
   * @return string
179
   */
180
  public static function URI(){
181
    switch(true){
182
      case !empty($_SERVER['REQUEST_URI']):    $serv_uri = $_SERVER['REQUEST_URI']; break;
183
      case !empty($_SERVER['ORIG_PATH_INFO']): $serv_uri = $_SERVER['ORIG_PATH_INFO']; break;
184
      case !empty($_SERVER['PATH_INFO']):      $serv_uri = $_SERVER['PATH_INFO']; break;
185
      default:                                 $serv_uri = '/'; break;
186
    }
187
    $uri = rtrim(strtok($serv_uri,'?'),'/') ?: '/';
188
    return Filter::with('core.request.URI', $uri) ?: '/';
189
  }
190
191
  /**
192
   * Returns the current base URI (The front-controller directory)
193
   *
194
   * @return string
195
   */
196
  public static function baseURI(){
197
    return dirname(empty($_SERVER['SCRIPT_NAME']) ? $_SERVER['PHP_SELF'] : $_SERVER['SCRIPT_NAME']) ?: '/';
198
  }
199
200
  /**
201
   * Returns the HTTP Method
202
   *
203
   * @return string
204
   */
205
  public static function method(){
206
   return Filter::with('core.request.method',strtolower(empty($_SERVER['REQUEST_METHOD'])?'get':$_SERVER['REQUEST_METHOD']));
207
  }
208
209
  /**
210
   * Returns the remote IP
211
   *
212
   * @return string
213
   */
214
  public static function IP(){
215
   switch(true){
216 View Code Duplication
     case !empty($_SERVER['HTTP_X_FORWARDED_FOR']):
217
       $ip = trim(substr(strrchr($_SERVER['HTTP_X_FORWARDED_FOR'],','),1) ?: $_SERVER['HTTP_X_FORWARDED_FOR']);
218
     break;
219 View Code Duplication
     case !empty($_SERVER['HTTP_X_FORWARDED_HOST']):
220
       $ip = trim(substr(strrchr($_SERVER['HTTP_X_FORWARDED_HOST'],','),1) ?: $_SERVER['HTTP_X_FORWARDED_HOST']);
221
     break;
222
     case !empty($_SERVER['REMOTE_ADDR']):    $ip = $_SERVER['REMOTE_ADDR']; break;
223
     case !empty($_SERVER['HTTP_CLIENT_IP']): $ip = $_SERVER['HTTP_CLIENT_IP']; break;
224
     default:                                 $ip = ''; break;
225
   }
226
   return Filter::with('core.request.IP',$ip);
227
  }
228
229
  /**
230
   * Returns the remote UserAgent
231
   *
232
   * @return string
233
   */
234
  public static function UA(){
235
   return Filter::with('core.request.UA',strtolower(empty($_SERVER['HTTP_USER_AGENT'])?'':$_SERVER['HTTP_USER_AGENT']));
236
  }
237
238
  /**
239
   * Returns request body data, convert to object if content type is JSON
240
   * Gives you all request data if you pass `null` as $key
241
   *
242
   * @param  string $key The name of the key requested
243
   *
244
   * @return mixed The request body data
245
   */
246
  public static function data($key=null,$default=null){
247
    if (null===static::$body){
248
      $json = (false !== stripos(empty($_SERVER['HTTP_CONTENT_TYPE'])?'':$_SERVER['HTTP_CONTENT_TYPE'],'json'))
249
           || (false !== stripos(empty($_SERVER['CONTENT_TYPE'])?'':$_SERVER['CONTENT_TYPE'],'json'));
250
      if ($json) {
251
        static::$body = json_decode(file_get_contents("php://input"));
252
      } else {
253
       if (empty($_POST)) {
254
          static::$body = file_get_contents("php://input");
255
        } else {
256
          static::$body = (object)$_POST;
257
        }
258
      }
259
    }
260
    return $key ? (isset(static::$body->$key) ? static::$body->$key : (is_callable($default)?call_user_func($default):$default))  : static::$body;
261
  }
262
263
}
264