Passed
Push — master ( 9c20ed...2c5d5d )
by Fran
04:30
created

Request::isLoaded()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

Changes 0
Metric Value
cc 1
eloc 2
nc 1
nop 0
dl 0
loc 3
ccs 2
cts 2
cp 1
crap 1
rs 10
c 0
b 0
f 0
1
<?php
2
3
namespace PSFS\base;
4
5
use PSFS\base\types\SingletonTrait;
6
7
if (!function_exists("getallheaders")) {
8
    function getallheaders()
9
    {
10 2
        $headers = array();
11 2
        foreach ($_SERVER as $h => $v)
12 2
            if (preg_match('/HTTP_(.+)/', $h, $hp))
13 2
                $headers[$hp[1]] = $v;
14 2
        return $headers;
15
    }
16
}
17
18
/**
19
 * Class Request
20
 * @package PSFS
21
 */
22
class Request
23
{
24
    use SingletonTrait;
25
    protected $server;
26
    protected $cookies;
27
    protected $upload;
28
    protected $header;
29
    protected $data;
30
    protected $query;
31
    private $isLoaded = false;
32
33 2
    public function init()
0 ignored issues
show
Coding Style introduced by
init uses the super-global variable $_SERVER which is generally not recommended.

Instead of super-globals, we recommend to explicitly inject the dependencies of your class. This makes your code less dependent on global state and it becomes generally more testable:

// Bad
class Router
{
    public function generate($path)
    {
        return $_SERVER['HOST'].$path;
    }
}

// Better
class Router
{
    private $host;

    public function __construct($host)
    {
        $this->host = $host;
    }

    public function generate($path)
    {
        return $this->host.$path;
    }
}

class Controller
{
    public function myAction(Request $request)
    {
        // Instead of
        $page = isset($_GET['page']) ? intval($_GET['page']) : 1;

        // Better (assuming you use the Symfony2 request)
        $page = $request->query->get('page', 1);
    }
}
Loading history...
Coding Style introduced by
init uses the super-global variable $_COOKIE which is generally not recommended.

Instead of super-globals, we recommend to explicitly inject the dependencies of your class. This makes your code less dependent on global state and it becomes generally more testable:

// Bad
class Router
{
    public function generate($path)
    {
        return $_SERVER['HOST'].$path;
    }
}

// Better
class Router
{
    private $host;

    public function __construct($host)
    {
        $this->host = $host;
    }

    public function generate($path)
    {
        return $this->host.$path;
    }
}

class Controller
{
    public function myAction(Request $request)
    {
        // Instead of
        $page = isset($_GET['page']) ? intval($_GET['page']) : 1;

        // Better (assuming you use the Symfony2 request)
        $page = $request->query->get('page', 1);
    }
}
Loading history...
Coding Style introduced by
init uses the super-global variable $_FILES which is generally not recommended.

Instead of super-globals, we recommend to explicitly inject the dependencies of your class. This makes your code less dependent on global state and it becomes generally more testable:

// Bad
class Router
{
    public function generate($path)
    {
        return $_SERVER['HOST'].$path;
    }
}

// Better
class Router
{
    private $host;

    public function __construct($host)
    {
        $this->host = $host;
    }

    public function generate($path)
    {
        return $this->host.$path;
    }
}

class Controller
{
    public function myAction(Request $request)
    {
        // Instead of
        $page = isset($_GET['page']) ? intval($_GET['page']) : 1;

        // Better (assuming you use the Symfony2 request)
        $page = $request->query->get('page', 1);
    }
}
Loading history...
Coding Style introduced by
init uses the super-global variable $_REQUEST which is generally not recommended.

Instead of super-globals, we recommend to explicitly inject the dependencies of your class. This makes your code less dependent on global state and it becomes generally more testable:

// Bad
class Router
{
    public function generate($path)
    {
        return $_SERVER['HOST'].$path;
    }
}

// Better
class Router
{
    private $host;

    public function __construct($host)
    {
        $this->host = $host;
    }

    public function generate($path)
    {
        return $this->host.$path;
    }
}

class Controller
{
    public function myAction(Request $request)
    {
        // Instead of
        $page = isset($_GET['page']) ? intval($_GET['page']) : 1;

        // Better (assuming you use the Symfony2 request)
        $page = $request->query->get('page', 1);
    }
}
Loading history...
Coding Style introduced by
init uses the super-global variable $_GET which is generally not recommended.

Instead of super-globals, we recommend to explicitly inject the dependencies of your class. This makes your code less dependent on global state and it becomes generally more testable:

// Bad
class Router
{
    public function generate($path)
    {
        return $_SERVER['HOST'].$path;
    }
}

// Better
class Router
{
    private $host;

    public function __construct($host)
    {
        $this->host = $host;
    }

    public function generate($path)
    {
        return $this->host.$path;
    }
}

class Controller
{
    public function myAction(Request $request)
    {
        // Instead of
        $page = isset($_GET['page']) ? intval($_GET['page']) : 1;

        // Better (assuming you use the Symfony2 request)
        $page = $request->query->get('page', 1);
    }
}
Loading history...
34
    {
35 2
        $this->server = $_SERVER or [];
0 ignored issues
show
Comprehensibility Best Practice introduced by
Using logical operators such as or instead of || is generally not recommended.

PHP has two types of connecting operators (logical operators, and boolean operators):

  Logical Operators Boolean Operator
AND - meaning and &&
OR - meaning or ||

The difference between these is the order in which they are executed. In most cases, you would want to use a boolean operator like &&, or ||.

Let’s take a look at a few examples:

// Logical operators have lower precedence:
$f = false or true;

// is executed like this:
($f = false) or true;


// Boolean operators have higher precedence:
$f = false || true;

// is executed like this:
$f = (false || true);

Logical Operators are used for Control-Flow

One case where you explicitly want to use logical operators is for control-flow such as this:

$x === 5
    or die('$x must be 5.');

// Instead of
if ($x !== 5) {
    die('$x must be 5.');
}

Since die introduces problems of its own, f.e. it makes our code hardly testable, and prevents any kind of more sophisticated error handling; you probably do not want to use this in real-world code. Unfortunately, logical operators cannot be combined with throw at this point:

// The following is currently a parse error.
$x === 5
    or throw new RuntimeException('$x must be 5.');

These limitations lead to logical operators rarely being of use in current PHP code.

Loading history...
36 2
        $this->cookies = $_COOKIE or [];
0 ignored issues
show
Comprehensibility Best Practice introduced by
Using logical operators such as or instead of || is generally not recommended.

PHP has two types of connecting operators (logical operators, and boolean operators):

  Logical Operators Boolean Operator
AND - meaning and &&
OR - meaning or ||

The difference between these is the order in which they are executed. In most cases, you would want to use a boolean operator like &&, or ||.

Let’s take a look at a few examples:

// Logical operators have lower precedence:
$f = false or true;

// is executed like this:
($f = false) or true;


// Boolean operators have higher precedence:
$f = false || true;

// is executed like this:
$f = (false || true);

Logical Operators are used for Control-Flow

One case where you explicitly want to use logical operators is for control-flow such as this:

$x === 5
    or die('$x must be 5.');

// Instead of
if ($x !== 5) {
    die('$x must be 5.');
}

Since die introduces problems of its own, f.e. it makes our code hardly testable, and prevents any kind of more sophisticated error handling; you probably do not want to use this in real-world code. Unfortunately, logical operators cannot be combined with throw at this point:

// The following is currently a parse error.
$x === 5
    or throw new RuntimeException('$x must be 5.');

These limitations lead to logical operators rarely being of use in current PHP code.

Loading history...
37 2
        $this->upload = $_FILES or [];
0 ignored issues
show
Comprehensibility Best Practice introduced by
Using logical operators such as or instead of || is generally not recommended.

PHP has two types of connecting operators (logical operators, and boolean operators):

  Logical Operators Boolean Operator
AND - meaning and &&
OR - meaning or ||

The difference between these is the order in which they are executed. In most cases, you would want to use a boolean operator like &&, or ||.

Let’s take a look at a few examples:

// Logical operators have lower precedence:
$f = false or true;

// is executed like this:
($f = false) or true;


// Boolean operators have higher precedence:
$f = false || true;

// is executed like this:
$f = (false || true);

Logical Operators are used for Control-Flow

One case where you explicitly want to use logical operators is for control-flow such as this:

$x === 5
    or die('$x must be 5.');

// Instead of
if ($x !== 5) {
    die('$x must be 5.');
}

Since die introduces problems of its own, f.e. it makes our code hardly testable, and prevents any kind of more sophisticated error handling; you probably do not want to use this in real-world code. Unfortunately, logical operators cannot be combined with throw at this point:

// The following is currently a parse error.
$x === 5
    or throw new RuntimeException('$x must be 5.');

These limitations lead to logical operators rarely being of use in current PHP code.

Loading history...
38 2
        $this->header = $this->parseHeaders();
39 2
        $this->data = $_REQUEST or [];
0 ignored issues
show
Comprehensibility Best Practice introduced by
Using logical operators such as or instead of || is generally not recommended.

PHP has two types of connecting operators (logical operators, and boolean operators):

  Logical Operators Boolean Operator
AND - meaning and &&
OR - meaning or ||

The difference between these is the order in which they are executed. In most cases, you would want to use a boolean operator like &&, or ||.

Let’s take a look at a few examples:

// Logical operators have lower precedence:
$f = false or true;

// is executed like this:
($f = false) or true;


// Boolean operators have higher precedence:
$f = false || true;

// is executed like this:
$f = (false || true);

Logical Operators are used for Control-Flow

One case where you explicitly want to use logical operators is for control-flow such as this:

$x === 5
    or die('$x must be 5.');

// Instead of
if ($x !== 5) {
    die('$x must be 5.');
}

Since die introduces problems of its own, f.e. it makes our code hardly testable, and prevents any kind of more sophisticated error handling; you probably do not want to use this in real-world code. Unfortunately, logical operators cannot be combined with throw at this point:

// The following is currently a parse error.
$x === 5
    or throw new RuntimeException('$x must be 5.');

These limitations lead to logical operators rarely being of use in current PHP code.

Loading history...
40 2
        $this->query = $_GET or [];
0 ignored issues
show
Comprehensibility Best Practice introduced by
Using logical operators such as or instead of || is generally not recommended.

PHP has two types of connecting operators (logical operators, and boolean operators):

  Logical Operators Boolean Operator
AND - meaning and &&
OR - meaning or ||

The difference between these is the order in which they are executed. In most cases, you would want to use a boolean operator like &&, or ||.

Let’s take a look at a few examples:

// Logical operators have lower precedence:
$f = false or true;

// is executed like this:
($f = false) or true;


// Boolean operators have higher precedence:
$f = false || true;

// is executed like this:
$f = (false || true);

Logical Operators are used for Control-Flow

One case where you explicitly want to use logical operators is for control-flow such as this:

$x === 5
    or die('$x must be 5.');

// Instead of
if ($x !== 5) {
    die('$x must be 5.');
}

Since die introduces problems of its own, f.e. it makes our code hardly testable, and prevents any kind of more sophisticated error handling; you probably do not want to use this in real-world code. Unfortunately, logical operators cannot be combined with throw at this point:

// The following is currently a parse error.
$x === 5
    or throw new RuntimeException('$x must be 5.');

These limitations lead to logical operators rarely being of use in current PHP code.

Loading history...
41 2
        $contentType = (array_key_exists('Content-Type', $this->header)) ? $this->header['Content-Type'] : "text/html";
42 2
        if (preg_match('/application\/json/i', $contentType)) {
43
            $this->data += json_decode(file_get_contents("php://input"), true) ?: array();
44
        }
45 2
        $this->isLoaded = true;
46 2
    }
47
48
    /**
49
     * @return bool
50
     */
51 1
    public function isLoaded() {
52 1
        return $this->isLoaded;
53
    }
54
55
    /**
56
     * Método que devuelve las cabeceras de la petición
57
     * @return array
58
     */
59 2
    private function parseHeaders()
60
    {
61 2
        return getallheaders();
62
    }
63
64
    /**
65
     * Método que verifica si existe una cabecera concreta
66
     * @param $header
67
     *
68
     * @return boolean
69
     */
70 1
    public function hasHeader($header)
71
    {
72 1
        return array_key_exists($header, $this->header);
73
    }
74
75
76
    /**
77
     * Método que indica si una petición tiene cookies
78
     * @return boolean
79
     */
80 1
    public function hasCookies()
81
    {
82 1
        return (null !== $this->cookies && 0 !== count($this->cookies));
83
    }
84
85
    /**
86
     * Método que indica si una petición tiene cookies
87
     * @return boolean
88
     */
89 1
    public function hasUpload()
90
    {
91 1
        return (null !== $this->upload && 0 !== count($this->upload));
92
    }
93
94
    /**
95
     * Método que devuelve el TimeStamp de la petición
96
     *
97
     * @param boolean $formatted
98
     *
99
     * @return string
100
     */
101
    public static function ts($formatted = false)
102
    {
103
        return self::getInstance()->getTs($formatted);
104
    }
105
106 1
    public function getTs($formatted = false)
0 ignored issues
show
Documentation introduced by
The return type could not be reliably inferred; please add a @return annotation.

Our type inference engine in quite powerful, but sometimes the code does not provide enough clues to go by. In these cases we request you to add a @return annotation as described here.

Loading history...
107
    {
108 1
        return ($formatted) ? date('Y-m-d H:i:s', $this->server['REQUEST_TIME_FLOAT']) : $this->server['REQUEST_TIME_FLOAT'];
0 ignored issues
show
Coding Style introduced by
This line exceeds maximum limit of 120 characters; contains 125 characters

Overly long lines are hard to read on any screen. Most code styles therefor impose a maximum limit on the number of characters in a line.

Loading history...
109
    }
110
111
    /**
112
     * Método que devuelve el Método HTTP utilizado
113
     * @return string
114
     */
115 3
    public function getMethod()
116
    {
117 3
        return (array_key_exists('REQUEST_METHOD', $this->server)) ? strtoupper($this->server['REQUEST_METHOD']) : 'GET';
0 ignored issues
show
Coding Style introduced by
This line exceeds maximum limit of 120 characters; contains 121 characters

Overly long lines are hard to read on any screen. Most code styles therefor impose a maximum limit on the number of characters in a line.

Loading history...
118
    }
119
120
    /**
121
     * Método que devuelve una cabecera de la petición si existe
122
     * @param $name
123
     *
124
     * @return string|null
125
     */
126
    public static function header($name)
127
    {
128
        return self::getInstance()->getHeader($name);
129
    }
130
131
    public function getHeader($name)
0 ignored issues
show
Documentation introduced by
The return type could not be reliably inferred; please add a @return annotation.

Our type inference engine in quite powerful, but sometimes the code does not provide enough clues to go by. In these cases we request you to add a @return annotation as described here.

Loading history...
132
    {
133
        $header = null;
134
        if ($this->hasHeader($name)) {
135
            $header = $this->header[$name];
136
        }
137
        return $header;
138
    }
139
140
    /**
141
     * Método que devuelve la url solicitada
142
     * @return string|null
143
     */
144
    public static function requestUri()
145
    {
146
        return self::getInstance()->getRequestUri();
147
    }
148
149
    /**
150
     * @return string
151
     */
152 6
    public function getRequestUri()
153
    {
154 6
        return array_key_exists('REQUEST_URI', $this->server) ? $this->server['REQUEST_URI'] : '';
155
    }
156
157
    /**
158
     * Método que devuelve el idioma de la petición
159
     * @return string
160
     */
161
    public function getLanguage()
162
    {
163
        return array_key_exists('HTTP_ACCEPT_LANGUAGE', $this->server) ? $this->server['HTTP_ACCEPT_LANGUAGE'] : 'es_ES';
0 ignored issues
show
Coding Style introduced by
This line exceeds maximum limit of 120 characters; contains 121 characters

Overly long lines are hard to read on any screen. Most code styles therefor impose a maximum limit on the number of characters in a line.

Loading history...
164
    }
165
166
    /**
167
     * Método que determina si se ha solicitado un fichero
168
     * @return boolean
169
     */
170 4
    public function isFile()
171
    {
172 4
        $file = (preg_match('/\.[a-z0-9]{2,4}$/', $this->getRequestUri()) !== 0);
173 4
        return $file;
174
    }
175
176
    /**
177
     * Get query params
178
     *
179
     * @param string $queryParams
180
     *
181
     * @return mixed
182
     */
183
    public function getQuery($queryParams)
184
    {
185
        return (array_key_exists($queryParams, $this->query)) ? $this->query[$queryParams] : null;
186
    }
187
188
    /**
189
     * Get all query params
190
     *
191
     * @return mixed
192
     */
193
    public function getQueryParams()
194
    {
195
        return $this->query;
196
    }
197
198
    /**
199
     * Método que devuelve un parámetro de la solicitud
200
     * @param string $param
201
     *
202
     * @return string|null
203
     */
204
    public function get($param)
205
    {
206
        return (array_key_exists($param, $this->data)) ? $this->data[$param] : null;
207
    }
208
209
    /**
210
     * Método que devuelve todos los datos del Request
211
     * @return array
212
     */
213
    public function getData()
214
    {
215
        return $this->data;
216
    }
217
218
    /**
219
     * Método que realiza una redirección a la url dada
220
     * @param string $url
221
     */
222
    public function redirect($url = null)
223
    {
224
        if (null === $url) $url = $this->getServer('HTTP_ORIGIN');
225
        ob_start();
226
        header('Location: ' . $url);
227
        ob_end_clean();
228
        Security::getInstance()->updateSession();
229
        exit(_("Redireccionando..."));
230
    }
231
232
    /**
233
     * Devuelve un parámetro de $_SERVER
234
     * @param string $param
235
     *
236
     * @return string|null
237
     */
238 3
    public function getServer($param)
239
    {
240 3
        return array_key_exists($param, $this->server) ? $this->server[$param] : null;
241
    }
242
243
    /**
244
     * Devuelve el nombre del servidor
245
     * @return string|null
246
     */
247
    public function getServerName()
248
    {
249
        return $this->getServer("SERVER_NAME");
250
    }
251
252
    /**
253
     * Devuelve el protocolo de la conexión
254
     * @return string
255
     */
256
    public function getProtocol()
257
    {
258
        return ($this->getServer("HTTPS") || $this->getServer("https")) ? 'https://' : 'http://';
259
    }
260
261
    /**
262
     * Devuelve la url completa de base
263
     * @param boolean $protocol
264
     * @return string
265
     */
266
    public function getRootUrl($protocol = true)
267
    {
268
        $host = $this->getServerName();
269
        $protocol = $protocol ? $this->getProtocol() : '';
270
        $url = '';
271
        if (!empty($host) && !empty($protocol)) $url = $protocol . $host;
272
        if (!in_array($this->getServer('SERVER_PORT'), [80, 443])) {
273
            $url .= ':' . $this->getServer('SERVER_PORT');
274
        }
275
        return $url;
276
    }
277
278
    /**
279
     * Método que devuelve el valor de una cookie en caso de que exista
280
     * @param string $name
281
     *
282
     * @return string
283
     */
284 1
    public function getCookie($name)
285
    {
286 1
        return array_key_exists($name, $this->cookies) ? $this->cookies[$name] : null;
287
    }
288
289
    /**
290
     * Método que devuelve los files subidos por POST
291
     * @param $name
292
     *
293
     * @return array
294
     */
295
    public function getFile($name)
296
    {
297
        return array_key_exists($name, $this->upload) ? $this->upload[$name] : array();
298
    }
299
300
    /**
301
     * Método que devuelve si la petición es ajax o no
302
     * @return boolean
303
     */
304 1
    public function isAjax()
305
    {
306 1
        $requested = $this->getServer("HTTP_X_REQUESTED_WITH");
307 1
        return (null !== $requested && strtolower($requested) == 'xmlhttprequest');
308
    }
309
310
}
311