1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace pjpawel\LightApi\Http; |
4
|
|
|
|
5
|
|
|
use pjpawel\LightApi\Http\Exception\ForbiddenHttpException; |
6
|
|
|
use Psr\Log\LoggerInterface; |
7
|
|
|
|
8
|
|
|
/** |
9
|
|
|
* @phpstan-consistent-constructor |
10
|
|
|
*/ |
11
|
|
|
class Request |
12
|
|
|
{ |
13
|
|
|
public string $ip; |
14
|
|
|
public string $path; |
15
|
|
|
public string $method; |
16
|
|
|
public ValuesBag $query; |
17
|
|
|
public ValuesBag $request; |
18
|
|
|
public ValuesBag $attributes; |
19
|
|
|
public ValuesBag $server; |
20
|
|
|
public ValuesBag $files; |
21
|
|
|
public ValuesBag $cookies; |
22
|
|
|
public ?string $content; |
23
|
|
|
|
24
|
|
|
public function __construct( |
25
|
|
|
array $query = [], |
26
|
|
|
array $request = [], |
27
|
|
|
array $cookies = [], |
28
|
|
|
array $files = [], |
29
|
|
|
array $server = [], |
30
|
|
|
array $attributes = [], |
31
|
|
|
$content = null) |
32
|
|
|
{ |
33
|
|
|
$this->query = new ValuesBag($query); |
34
|
|
|
$this->request = new ValuesBag($request); |
35
|
|
|
$this->attributes = new ValuesBag($attributes); |
36
|
|
|
$this->server = new ValuesBag($server); |
37
|
|
|
$this->files = new ValuesBag($files); |
38
|
|
|
$this->cookies = new ValuesBag($cookies); |
39
|
|
|
$this->content = $content; |
40
|
|
|
|
41
|
|
|
$this->ip = $this->server->get('REMOTE_ADDR'); |
42
|
|
|
$this->path = $this->server->get('REQUEST_URI'); |
43
|
|
|
$this->method = $this->server->get('REQUEST_METHOD', 'GET'); |
44
|
|
|
} |
45
|
|
|
|
46
|
|
|
public static function makeFromGlobals(): static |
47
|
|
|
{ |
48
|
|
|
return new static($_GET, $_POST, $_COOKIE, $_FILES, $_SERVER); |
49
|
|
|
} |
50
|
|
|
|
51
|
|
|
/** |
52
|
|
|
* @param array $trustedIPs |
53
|
|
|
* @return void |
54
|
|
|
* @throws ForbiddenHttpException |
55
|
|
|
*/ |
56
|
|
|
public function validateIp(array $trustedIPs = []): void |
57
|
|
|
{ |
58
|
|
|
if (empty($trustedIPs)) { |
59
|
|
|
return; |
60
|
|
|
} |
61
|
|
|
if (!in_array($this->ip, $trustedIPs)) { |
62
|
|
|
throw new ForbiddenHttpException(); |
63
|
|
|
} |
64
|
|
|
} |
65
|
|
|
|
66
|
|
|
public function logRequest(?LoggerInterface $logger): void |
67
|
|
|
{ |
68
|
|
|
$logger?->info( |
69
|
|
|
sprintf('Requested path: %s, with %s method from ip: %s', |
70
|
|
|
$this->path, $this->method, $this->ip) |
71
|
|
|
); |
72
|
|
|
} |
73
|
|
|
} |