Test Failed
Push — master ( 1a1353...98dc9d )
by Fran
03:27
created

Request::getCookie()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 6

Importance

Changes 0
Metric Value
cc 2
eloc 2
c 0
b 0
f 0
nc 2
nop 1
dl 0
loc 4
ccs 0
cts 1
cp 0
crap 6
rs 10
1
<?php
2
namespace PSFS\base;
3
4
use PSFS\base\types\traits\SingletonTrait;
5
6
/**
7
 * Class Request
8
 * @package PSFS
9
 */
10
class Request
11
{
12
    use SingletonTrait;
13
    protected $server;
14
    protected $cookies;
15
    protected $upload;
16
    protected $header;
17
    protected $data;
18
    protected $raw = [];
19
    protected $query;
20
    private $isLoaded = false;
21 2
22
    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...
23 2
    {
24 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...
25 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...
26 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...
27 2
        $this->header = $this->parseHeaders();
28 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...
29 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...
30 2
        $this->raw = json_decode(file_get_contents("php://input"), true) ?: [];
31 2
        $this->isLoaded = true;
32 2
    }
33 2
34
    /**
35
     * @return bool
36 2
     */
37 2
    public function isLoaded() {
38
        return $this->isLoaded;
39
    }
40
41
    /**
42 1
     * Método que devuelve las cabeceras de la petición
43 1
     * @return array
44
     */
45
    private function parseHeaders()
46
    {
47
        return getallheaders();
48
    }
49
50 2
    /**
51
     * Método que verifica si existe una cabecera concreta
52 2
     * @param $header
53
     *
54
     * @return boolean
55
     */
56
    public function hasHeader($header)
57
    {
58
        return array_key_exists($header, $this->header);
59
    }
60
61 3
62
    /**
63 3
     * Método que indica si una petición tiene cookies
64
     * @return boolean
65
     */
66
    public function hasCookies()
67
    {
68
        return (null !== $this->cookies && 0 !== count($this->cookies));
69
    }
70
71 1
    /**
72
     * Método que indica si una petición tiene cookies
73 1
     * @return boolean
74
     */
75
    public function hasUpload()
76
    {
77
        return (null !== $this->upload && 0 !== count($this->upload));
78
    }
79
80 1
    /**
81
     * Método que devuelve el TimeStamp de la petición
82 1
     *
83
     * @param boolean $formatted
84
     *
85
     * @return string
86
     */
87
    public static function ts($formatted = false)
88
    {
89
        return self::getInstance()->getTs($formatted);
90
    }
91
92
    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...
93
    {
94
        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...
95
    }
96
97 1
    /**
98
     * Método que devuelve el Método HTTP utilizado
99 1
     * @return string
100
     */
101
    public function getMethod()
102
    {
103
        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...
104
    }
105
106 4
    /**
107
     * Método que devuelve una cabecera de la petición si existe
108 4
     * @param string $name
109
     * @param string $default
0 ignored issues
show
Documentation introduced by
Should the type for parameter $default not be string|null?

This check looks for @param annotations where the type inferred by our type inference engine differs from the declared type.

It makes a suggestion as to what type it considers more descriptive.

Most often this is a case of a parameter that can be null in addition to its declared types.

Loading history...
110
     *
111
     * @return string|null
112
     */
113
    public static function header($name, $default = null)
114
    {
115
        return self::getInstance()->getHeader($name,  $default);
116
    }
117
118
    /**
119
     * @param string $name
120
     * @param string $default
0 ignored issues
show
Documentation introduced by
Should the type for parameter $default not be string|null?

This check looks for @param annotations where the type inferred by our type inference engine differs from the declared type.

It makes a suggestion as to what type it considers more descriptive.

Most often this is a case of a parameter that can be null in addition to its declared types.

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