-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathRequest.php
More file actions
413 lines (358 loc) · 11.1 KB
/
Copy pathRequest.php
File metadata and controls
413 lines (358 loc) · 11.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
<?php
namespace Mk4U\Http;
/**
* Request class
*/
class Request
{
/** @param array $files datos de carga de archivos*/
private array $files;
/** @param string $method Metodo HTTP*/
private string $method;
/** @param Uri $uri instancia de la clase Mk4u\Http\Uri */
private Uri $uri;
/** @param array $form_content_type datos pasados por formulario(POST) */
private array $form_content_type = ['application/x-www-form-urlencoded', 'multipart/form-data'];
/** @param mixed $content Contenido de la solicitud HTTP */
private mixed $content = null;
use Headers;
/**
* Crea un nuevo objeto Request
*/
public function __construct(
string $method,
string|Uri $uri,
array $headers = [],
$body = null,
?string $version = null
) {
//metodo
$this->setMethod($method);
// URI
$this->setUri(
$uri instanceof Uri ? $uri : new Uri($uri)
);
//Headers
$this->setHeaders($headers);
//Content
$this->content = $body;
//Vesion Http
$this->setProtocolVersion($version);
}
/**
* Debuguear solicitud HTTP
*/
public function __debugInfo(): array
{
return [
"method" => $this->getMethod(),
"uri" => $this->getUri(),
"protocol" => $this->getProtocolVersion(),
"headers" => $this->getHeaders(),
"content" => $this->content
];
}
/**
* Crea un nuevo objeto Request a partir de las superglobales
*/
public static function create(): static
{
$uri = self::createUri();
$headers = function_exists('getallheaders') ? getallheaders() : [];
$request = new static(
self::server('request_method','GET'),
$uri,
$headers
);
$request->getContent();
return $request;
}
/**
* Crea un objeto Uri a partir del array $_SERVER
*/
private static function createUri(): Uri
{
$server = self::server();
[$user, $pass] = self::fetchUserInfo($server);
$uri = (new Uri())
->withScheme(self::fetchScheme($server))
->withHost(self::fetchHost($server))
->withPort(self::fetchPort($server))
->withPath(self::fetchPath($server))
->withQuery(self::fetchQuery($server));
if ($user !== null) {
$uri = $uri->withUserInfo($user, $pass);
}
return $uri;
}
/**
* Devuelve parametros del $_SERVER.
*/
public static function server(?string $index = null, mixed $default = null, bool $all = false): mixed
{
if ($all || $index === null) {
return $_SERVER;
}
return $_SERVER[strtoupper($index)] ?? $default;
}
/**
* Obtiene Ip del cliente
*/
public static function getClientIp(): string
{
return self::server('HTTP_CLIENT_IP')
?? self::server('HTTP_X_FORWARDED_FOR')
?? self::server('HTTP_X_REAL_IP')
?? self::server('REMOTE_ADDR')
?? '0.0.0.0';
}
/**
* Obtener solicitud de destino
*
* @see http://tools.ietf.org/html/rfc7230#section-5.3
*/
public function getTarget(): string
{
$target = $this->uri->getPath();
return ($target !== '') ? $target : '/';
}
/**
* Obtener metodo http
*/
public function getMethod(): string
{
return $this->method;
}
/**
* Establecer metodo http
*/
public function setMethod(string $method): static
{
$this->method = strtoupper($method);
return $this;
}
/**
* Verificar metodo http
*/
public function hasMethod(string $method): bool
{
return strcasecmp($this->method, $method) === 0;
}
/**
* Obtener Uri
*/
public function getUri(): Uri
{
return $this->uri;
}
/**
* Establecer Uri
*/
public function setUri(Uri $uri, bool $preserveHost = false): static
{
$this->uri = $uri;
if (!$preserveHost || !$this->hasHeader('host') || $this->getHeaderLine('host') === '') {
$this->setHeader('host', $uri->getHost());
}
return $this;
}
/**
* Obtener cuerpo del mensaje HTTP
*/
private function getContent(): void
{
//contenido
if (
in_array($this->getMethod(), ['PUT', 'DELETE', 'PATCH'], true)
||
($this->hasMethod('POST') && !$this->isFormData())
) {
$this->content = file_get_contents('php://input');
}
//archivos
if ($this->isFormData() && $_FILES) {
$this->normalizeFiles($_FILES);
}
}
/**
* Determina si los valores son pasados a traves de un formulario
*/
public function isFormData(): bool
{
$content_type = explode(';', $this->getHeaderLine('content-type'))[0];
return ($this->hasMethod('POST') && in_array($content_type, $this->form_content_type, true));
}
/**
* Obtener parámetros
*
* En caso de no especificar el parametro a devolver, devuelve todos los valores
* del $params propiedad.
*
* Puede agregarle valores por defecto en caso de
* que $params[$name] no este definido.
**/
private function params(array $params, ?string $name = null, mixed $default = null): mixed
{
if (empty($name)) {
return $params;
}
return $params[$name] ?? $default;
}
/**
* Obtener parámetros en la cadena de consulta de la URI
*
* En caso de no especificar el parametro a devolver este metodo
* devuelve todos los valores de la superglobal $_GET.
*
* Puede agregarle valores a $_GET especificando
* el nombre del parametro y el valor.
*
* Tenga en cuenta que funciona para todas las solicitudes con una cadena de consulta.
**/
public function queryData(?string $name = null, mixed $default = null): mixed
{
return $this->params($_GET, $name, $default);
}
/**
* Recuperar los parámetros proporcionados en el cuerpo de la solicitud.
*
* Si el tipo de contenido de la solicitud es application/x-www-form-urlencoded
* o multipart/form-data, y el método de solicitud es POST, este método DEBE
* devolver el contenido de $_POST.
*
* De lo contrario, este método puede devolver cualquier resultado de deserializar
* el contenido del cuerpo de la solicitud; como el análisis devuelve contenido estructurado, el
* los tipos potenciales DEBEN ser matrices u objetos solamente. Un valor nulo indica
* la ausencia de contenido corporal.
**/
public function inputData(?string $name = null, mixed $default = null): mixed
{
if ($this->isFormData()) {
return $this->params($_POST, $name, $default);
}
//Si hay contenido en la propiedad content, intentamos deserializarlo
if ($this->content !== null) {
parse_str($this->content, $output);
return $this->params($output, $name, $default);
}
//Si no hay contenido, devolvemos null o el valor por defecto
return $default;
}
/**
* Devuelve JSON decodificado
*/
public function jsonData(bool $assoc = true): array|object|null
{
if (str_contains($this->getHeaderLine('content-type'), 'application/json')) {
return json_decode($this->content, $assoc, flags: JSON_THROW_ON_ERROR);
}
return null;
}
/**
* Devuelve el cuerpo de la solicitud sin tratar
*/
public function rawData(): ?string
{
return $this->content;
}
/**
* Obtiene ficheros subidos al servidor
*/
public function files(): array
{
return $this->files ?? [];
}
private static function fetchScheme(array $server): string
{
if (!empty($server['HTTPS']) && filter_var($server['HTTPS'], FILTER_VALIDATE_BOOLEAN)) {
return 'https';
}
return 'http';
}
private static function fetchHost(array $server): string
{
if (!empty($server['HTTP_HOST'])) {
return preg_replace('/:\d+$/', '', $server['HTTP_HOST']);
}
return $server['SERVER_NAME'] ?? 'localhost';
}
private static function fetchPort(array $server): ?int
{
if (!empty($server['HTTP_HOST']) && preg_match('/:(\d+)$/', $server['HTTP_HOST'], $m)) {
return (int) $m[1];
}
if (!empty($server['SERVER_PORT'])) {
return (int) $server['SERVER_PORT'];
}
return null;
}
private static function fetchPath(array $server): string
{
$path = $server['REQUEST_URI'] ?? $server['PHP_SELF'] ?? '/';
$path = parse_url($path, PHP_URL_PATH);
return $path !== false && $path !== null ? $path : '/';
}
private static function fetchQuery(array $server): string
{
if (!empty($server['QUERY_STRING'])) {
return $server['QUERY_STRING'];
}
if (!empty($server['REQUEST_URI'])) {
$parts = explode('?', $server['REQUEST_URI'], 2);
return $parts[1] ?? '';
}
return '';
}
private static function fetchUserInfo(array $server): array
{
$user = $server['PHP_AUTH_USER'] ?? null;
$pass = $server['PHP_AUTH_PW'] ?? null;
if (
!empty($server['HTTP_AUTHORIZATION'])
&& str_starts_with(strtolower($server['HTTP_AUTHORIZATION']), 'basic')
) {
$decoded = base64_decode(substr($server['HTTP_AUTHORIZATION'], 6), true);
if ($decoded !== false) {
$parts = explode(':', $decoded, 2);
$user = $parts[0];
$pass = $parts[1] ?? null;
}
}
return [$user, $pass];
}
/**
* Crea una instancia del objeto UploadedFile
*/
private static function createUploadedFile(array $value): UploadedFile
{
return new UploadedFile(
$value["tmp_name"],
$value["size"],
$value["name"],
$value["type"],
$value["error"]
);
}
/**
* Normaliza archivos enviados por $_FILES
*/
private function normalizeFiles(array $uploadFiles): void
{
//archivos
foreach ($uploadFiles as $key => $file) {
if (is_array($file['name'])) {
foreach ($file['name'] as $i => $name) {
$this->files[$key][] = self::createUploadedFile([
'name' => $file['name'][$i] ?? null,
'type' => $file['type'][$i] ?? null,
'tmp_name' => $file['tmp_name'][$i] ?? null,
'error' => $file['error'][$i] ?? null,
'size' => $file['size'][$i] ?? null,
]);
}
} else {
$this->files[$key] = self::createUploadedFile($file);
}
}
}
}