-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathServerRequest.php
221 lines (197 loc) · 6.59 KB
/
ServerRequest.php
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
<?php
/*
* This file is part of the Koded package.
*
* (c) Mihail Binev <[email protected]>
*
* Please view the LICENSE distributed with this source code
* for the full copyright and license information.
*
*/
namespace Koded\Http;
use Koded\Http\Interfaces\Request;
use Psr\Http\Message\ServerRequestInterface;
class ServerRequest extends ClientRequest implements Request
{
use CookieTrait, FilesTrait, ValidatableTrait;
protected string $serverSoftware = '';
protected array $attributes = [];
protected array $queryParams = [];
protected object|array|null $parsedBody = null;
/**
* ServerRequest constructor.
*
* @param array $attributes
*/
public function __construct(array $attributes = [])
{
parent::__construct($_SERVER['REQUEST_METHOD'] ?? Request::GET, $this->buildUri());
$this->attributes = $attributes;
$this->extractHttpHeaders($_SERVER);
$this->extractServerData($_SERVER);
}
public function getServerParams(): array
{
return $_SERVER;
}
public function getQueryParams(): array
{
return $this->queryParams;
}
public function withQueryParams(array $query): static
{
$instance = clone $this;
$instance->queryParams = \array_merge($instance->queryParams, $query);
return $instance;
}
public function getParsedBody(): object|array|null
{
if ($this->useOnlyPost()) {
return $_POST;
}
if (false === empty($_POST)) {
return $_POST;
}
return $this->parsedBody;
}
public function withParsedBody($data): static
{
$instance = clone $this;
if ($this->useOnlyPost()) {
$instance->parsedBody = $_POST;
return $instance;
}
// If nothing is available for the body
if (null === $data) {
$instance->parsedBody = null;
return $instance;
}
// Supports array or iterable object
if (\is_iterable($data)) {
$instance->parsedBody = \is_array($data) ? $data : \iterator_to_array($data);
return $instance;
}
if (\is_object($data)) {
$instance->parsedBody = $data;
return $instance;
}
throw new \InvalidArgumentException(
\sprintf('Unsupported data provided (%s), Expects NULL, array or iterable', \gettype($data))
);
}
public function getAttributes(): array
{
return $this->attributes;
}
public function getAttribute($name, $default = null): mixed
{
return $this->attributes[$name] ?? $default;
}
public function withAttribute($name, $value): static
{
$instance = clone $this;
$instance->attributes[$name] = $value;
return $instance;
}
public function withoutAttribute($name): static
{
$instance = clone $this;
unset($instance->attributes[$name]);
return $instance;
}
public function withAttributes(array $attributes): static
{
$instance = clone $this;
foreach ($attributes as $name => $value) {
$instance->attributes[$name] = $value;
}
return $instance;
}
public function isXHR(): bool
{
return 'XMLHTTPREQUEST' === \strtoupper($_SERVER['HTTP_X_REQUESTED_WITH'] ?? '');
}
protected function buildUri(): Uri
{
if (\strpos($_SERVER['REQUEST_URI'] ?? '', '://')) {
return new Uri($_SERVER['REQUEST_URI']);
}
if ($host = $_SERVER['SERVER_NAME'] ?? $_SERVER['SERVER_ADDR'] ?? '') {
return new Uri('http' . ($_SERVER['HTTPS'] ?? $_SERVER['HTTP_X_FORWARDED_PROTO'] ?? false ? 's' : '')
. '://' . $host
. ':' . ($_SERVER['SERVER_PORT'] ?? 80)
. ($_SERVER['REQUEST_URI'] ?? '')
);
}
return new Uri($_SERVER['REQUEST_URI'] ?? '');
}
protected function extractHttpHeaders(array $server): void
{
foreach ($server as $k => $v) {
// Calisthenics :)
\str_starts_with($k, 'HTTP_') && $this->normalizeHeader(\str_replace('HTTP_', '', $k), $v, false);
}
if (isset($server['HTTP_IF_NONE_MATCH'])) {
// ETag workaround for various broken Apache2 versions
$this->headers['ETag'] = \str_replace('-gzip', '', $server['HTTP_IF_NONE_MATCH']);
$this->headersMap['etag'] = 'ETag';
}
if (isset($server['CONTENT_TYPE'])) {
$this->headers['Content-Type'] = \strtolower($server['CONTENT_TYPE']);
$this->headersMap['content-type'] = 'Content-Type';
}
$this->setHost();
}
protected function extractServerData(array $server): void
{
$this->protocolVersion = \str_ireplace('HTTP/', '', $server['SERVER_PROTOCOL'] ?? $this->protocolVersion);
$this->serverSoftware = $server['SERVER_SOFTWARE'] ?? '';
$this->queryParams = $_GET;
$this->cookieParams = $_COOKIE;
if (false === $this->isSafeMethod()) {
$this->parseInput();
}
if ($_FILES) {
$this->uploadedFiles = $this->parseUploadedFiles($_FILES);
}
}
/**
* Per recommendation:
*
* @return bool If the request Content-Type is either
* application/x-www-form-urlencoded or multipart/form-data
* and the request method is POST,
* then it MUST return the contents of $_POST
* @see ServerRequestInterface::withParsedBody()
*
* @see ServerRequestInterface::getParsedBody()
*/
protected function useOnlyPost(): bool
{
if (empty($contentType = $this->getHeaderLine('Content-Type'))) {
return false;
}
return $this->method === self::POST && (
\str_contains('application/x-www-form-urlencoded', $contentType) ||
\str_contains('multipart/form-data', $contentType));
}
/**
* Try to unserialize a JSON string or form encoded request body.
* Very useful if JavaScript app stringify objects in AJAX requests.
*/
protected function parseInput(): void
{
if (empty($input = $this->getRawInput())) {
return;
}
// Try JSON deserialization
$this->parsedBody = \json_decode($input, true, 512, JSON_BIGINT_AS_STRING);
if (null === $this->parsedBody) {
\parse_str($input, $this->parsedBody);
}
}
protected function getRawInput(): string
{
return \file_get_contents('php://input') ?: '';
}
}