Passed
Pull Request — master (#26)
by
unknown
14:17
created

Request   B

Complexity

Total Complexity 45

Size/Duplication

Total Lines 284
Duplicated Lines 0 %

Test Coverage

Coverage 64.47%

Importance

Changes 4
Bugs 0 Features 0
Metric Value
eloc 72
c 4
b 0
f 0
dl 0
loc 284
ccs 49
cts 76
cp 0.6447
rs 8.8
wmc 45

21 Methods

Rating   Name   Duplication   Size   Complexity  
A hasUpload() 0 3 2
A getTimestamp() 0 3 1
A hasHeader() 0 3 1
B init() 0 10 7
A getHeader() 0 11 5
A header() 0 3 1
A hasCookies() 0 3 2
A parseHeaders() 0 3 2
A getQueryParams() 0 3 1
A setLanguageHeader() 0 3 1
A getFile() 0 3 2
A getQuery() 0 3 2
A checkServerPort() 0 15 5
A redirect() 0 10 2
A getCookie() 0 3 2
A getRootUrl() 0 9 3
A isFile() 0 3 1
A requestUri() 0 3 1
A getRawData() 0 2 1
A get() 0 3 2
A getData() 0 3 1

How to fix   Complexity   

Complex Class

Complex classes like Request often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

While breaking up the class, it is a good idea to analyze how other classes use Request, and based on these observations, apply Extract Interface, too.

1
<?php
2
namespace PSFS\base;
3
4
use PSFS\base\types\traits\Helper\ServerTrait;
5
use PSFS\base\types\traits\SingletonTrait;
6
7
/**
8
 * Class Request
9
 * @package PSFS
10
 */
11
class Request
12
{
13
    use SingletonTrait;
14
    use ServerTrait;
15
16
    const VERB_GET = 'GET';
17
    const VERB_POST = 'POST';
18
    const VERB_PUT = 'PUT';
19
    const VERB_DELETE = 'DELETE';
20
    const VERB_OPTIONS = 'OPTIONS';
21
    const VERB_HEAD = 'HEAD';
22
    const VERB_PATCH = 'PATCH';
23
24
    /**
25
     * @var array
26
     */
27
    protected $cookies;
28
    /**
29
     * @var array
30
     */
31
    protected $upload;
32
    /**
33
     * @var array
34
     */
35
    protected $header;
36
    /**
37
     * @var array
38
     */
39
    protected $data;
40
    /**
41
     * @var array
42
     */
43
    protected $raw = [];
44
    /**
45
     * @var array
46
     */
47
    protected $query;
48
    /**
49
     * @var bool
50
     */
51
    private $isLoaded = false;
52
53 2
    public function init()
54
    {
55 2
        $this->setServer(is_array($_SERVER) ? $_SERVER : []);
56 2
        $this->cookies = is_array($_COOKIE) ? $_COOKIE : [];
57 2
        $this->upload = is_array($_FILES) ? $_FILES : [];
58 2
        $this->header = $this->parseHeaders();
59 2
        $this->data = is_array($_REQUEST) ? $_REQUEST : [];
60 2
        $this->query = is_array($_GET) ? $_GET : [];
61 2
        $this->raw = json_decode(file_get_contents('php://input'), true) ?: [];
62 2
        $this->isLoaded = true;
63
    }
64
65
    /**
66
     * Método que devuelve las cabeceras de la petición
67
     * @return array
68
     */
69 2
    private function parseHeaders()
70
    {
71 2
        return getallheaders() ?: [];
0 ignored issues
show
Bug Best Practice introduced by
The expression return getallheaders() ?: array() also could return the type true which is incompatible with the documented return type array.
Loading history...
72
    }
73
74
    /**
75
     * Método que verifica si existe una cabecera concreta
76
     * @param $header
77
     *
78
     * @return boolean
79
     */
80 5
    public function hasHeader($header)
81
    {
82 5
        return array_key_exists($header, $this->header);
83
    }
84
85
86
    /**
87
     * Método que indica si una petición tiene cookies
88
     * @return boolean
89
     */
90 1
    public function hasCookies()
91
    {
92 1
        return (null !== $this->cookies && 0 !== count($this->cookies));
93
    }
94
95
    /**
96
     * Método que indica si una petición tiene cookies
97
     * @return boolean
98
     */
99 1
    public function hasUpload()
100
    {
101 1
        return (null !== $this->upload && 0 !== count($this->upload));
102
    }
103
104
    /**
105
     * Método que devuelve el TimeStamp de la petición
106
     *
107
     * @param boolean $formatted
108
     *
109
     * @return string
110
     */
111
    public static function getTimestamp($formatted = false)
112
    {
113
        return self::getInstance()->getTs($formatted);
114
    }
115
116
    /**
117
     * Método que devuelve una cabecera de la petición si existe
118
     * @param string $name
119
     * @param string $default
120
     *
121
     * @return string|null
122
     */
123 4
    public static function header($name, $default = null)
124
    {
125 4
        return self::getInstance()->getHeader($name,  $default);
126
    }
127
128
    /**
129
     * @param string $name
130
     * @param string $default
131
     * @return string|null
132
     */
133 4
    public function getHeader($name, $default = null)
134
    {
135 4
        $header = null;
136 4
        if ($this->hasHeader($name)) {
137
            $header = $this->header[$name];
138 4
        } else if(array_key_exists('h_' . strtolower($name), $this->query)) {
139
            $header = $this->query['h_' . strtolower($name)];
140 4
        } else if(array_key_exists('HTTP_' . strtoupper(str_replace('-', '_', $name)), $this->server)) {
141
            $header = $this->getServer('HTTP_' . strtoupper(str_replace('-', '_', $name)));
142
        }
143 4
        return $header ?: $default;
144
    }
145
146
	/**
147
	 * @param string $language
148
	 * @return void
149
	 */
150
	public static function setLanguageHeader(string $language)
151
	{
152
		self::getInstance()->header['X-API-LANG'] = $language;
153
	}
154
155
    /**
156
     * Método que devuelve la url solicitada
157
     * @return string|null
158
     */
159 1
    public static function requestUri()
160
    {
161 1
        return self::getInstance()->getRequestUri();
162
    }
163
164
    /**
165
     * Método que determina si se ha solicitado un fichero
166
     * @return boolean
167
     */
168 5
    public function isFile()
169
    {
170 5
        return preg_match('/\.[a-z0-9]{2,4}$/', $this->getRequestUri()) !== 0;
171
    }
172
173
    /**
174
     * Get query params
175
     *
176
     * @param string $queryParams
177
     *
178
     * @return mixed
179
     */
180
    public function getQuery($queryParams)
181
    {
182
        return array_key_exists($queryParams, $this->query) ? $this->query[$queryParams] : null;
183
    }
184
185
    /**
186
     * Get all query params
187
     *
188
     * @return mixed
189
     */
190 5
    public function getQueryParams()
191
    {
192 5
        return $this->query;
193
    }
194
195
    /**
196
     * Método que devuelve un parámetro de la solicitud
197
     * @param string $param
198
     *
199
     * @return string|null
200
     */
201
    public function get($param)
202
    {
203
        return array_key_exists($param, $this->data) ? $this->data[$param] : null;
204
    }
205
206
    /**
207
     * Método que devuelve todos los datos del Request
208
     * @return array
209
     */
210 6
    public function getData()
211
    {
212 6
        return array_merge($this->data, $this->raw);
213
    }
214
215
    /**
216
     * @return array
217
     */
218
    public function getRawData() {
219
        return $this->raw;
220
    }
221
222
    /**
223
     * Método que devuelve el valor de una cookie en caso de que exista
224
     * @param string $name
225
     *
226
     * @return string
227
     */
228 2
    public function getCookie($name)
229
    {
230 2
        return array_key_exists($name, $this->cookies) ? $this->cookies[$name] : null;
231
    }
232
233
    /**
234
     * Método que devuelve los files subidos por POST
235
     * @param $name
236
     *
237
     * @return array
238
     */
239
    public function getFile($name)
240
    {
241
        return array_key_exists($name, $this->upload) ? $this->upload[$name] : array();
242
    }
243
244
    /**
245
     * Método que realiza una redirección a la url dada
246
     * @param string $url
247
     */
248
    public function redirect($url = null)
249
    {
250
        if (null === $url) {
251
            $url = $this->getServer('HTTP_ORIGIN');
252
        }
253
        ob_start();
254
        header('Location: ' . $url);
255
        ob_end_clean();
256
        Security::getInstance()->updateSession();
257
        exit(t('Redirect...'));
258
    }
259
260
    /**
261
     * Devuelve la url completa de base
262
     * @param boolean $hasProtocol
263
     * @return string
264
     */
265 2
    public function getRootUrl($hasProtocol = true)
266
    {
267 2
        $url = $this->getServerName();
268 2
        $protocol = $hasProtocol ? $this->getProtocol() : '';
269 2
        if (!empty($protocol)) {
270 2
            $url = $protocol . $url;
271
        }
272 2
        $url = $this->checkServerPort($url);
273 2
        return $url;
274
    }
275
276
    /**
277
     * @param string $url
278
     * @return string
279
     */
280 2
    protected function checkServerPort(string $url)
281
    {
282 2
        $port = (integer)$this->getServer('SERVER_PORT');
283 2
        $host = $this->getServer('HTTP_HOST');
284 2
        if(!empty($host)) {
285
            $parts = explode(':', $host);
286
            $hostPort = (integer)end($parts);
287
            if($hostPort !== $port && count($parts) > 1) {
288
                $port = $hostPort;
289
            }
290
        }
291 2
        if (!in_array($port, [80, 443], true)) {
292 2
            $url .= ':' . $port;
293
        }
294 2
        return $url;
295
    }
296
297
}
298