Skip to content

Commit 0b08049

Browse files
committed
Refactoring
1 parent 41e5219 commit 0b08049

File tree

1 file changed

+70
-113
lines changed

1 file changed

+70
-113
lines changed

src/Http/ServerRequestBuilder.php

Lines changed: 70 additions & 113 deletions
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,8 @@
1919
UploadedFileFactoryInterface,
2020
ServerRequestInterface,
2121
StreamInterface,
22-
UploadedFileInterface
22+
UploadedFileInterface,
23+
UriFactoryInterface
2324
};
2425
use InvalidArgumentException;
2526
use UnexpectedValueException;
@@ -55,29 +56,16 @@ class ServerRequestBuilder
5556

5657
private array $server;
5758

58-
/** @var ServerRequestFactoryInterface|StreamFactoryInterface|UploadedFileFactoryInterface */
59-
private $factory;
60-
61-
private string $method = 'GET';
62-
63-
private string $uri = '/';
64-
65-
private array $queryParams = [];
66-
67-
private string $protocolVer = '1.1';
59+
private ServerRequestInterface $request;
6860

69-
private array $headers = [];
61+
/** @var ServerRequestFactoryInterface|StreamFactoryInterface|UploadedFileFactoryInterface|UriFactoryInterface */
62+
private $factory;
7063

71-
private array $cookieParams = [];
64+
private ?StreamInterface $body = null;
7265

7366
/** @var null|array|object */
7467
private $parsedBody;
7568

76-
private ?StreamInterface $body = null;
77-
78-
/** @var UploadedFileInterface[] */
79-
private array $uploadedFiles = [];
80-
8169
public static function fromSapi(
8270
array $server,
8371
object $factory,
@@ -110,79 +98,53 @@ public function __construct(array $server, object $factory)
11098

11199
$this->server = $server;
112100
$this->factory = $factory;
101+
$this->request = $factory->createServerRequest('GET', '/', $server);
113102
}
114103

115104
public function build(): ServerRequestInterface
116105
{
117-
$request = $this->factory->createServerRequest($this->method, $this->uri, $this->server)
118-
->withProtocolVersion($this->protocolVer);
106+
if (empty($this->parsedBody) && ! empty((string) $this->body)) {
107+
$parser = (self::$preferredMediaParser)($this->request);
119108

120-
if (! empty($this->queryParams)) {
121-
$request = $request->withQueryParams($this->queryParams);
109+
$this->request = $this->request
110+
->withParsedBody($parser->parse((string) $this->body));
122111
}
123112

124-
if (! empty($this->headers)) {
125-
$request = $this->addHeadersToServerRequest($request);
126-
}
127-
128-
if (! empty($this->cookieParams)) {
129-
$request = $request->withCookieParams($this->cookieParams);
130-
}
131-
132-
$isBodyEmpty = (null === $this->body);
133-
134-
if (empty($this->parsedBody) && ! $isBodyEmpty) {
135-
$parser = (self::$preferredMediaParser)($request);
136-
$this->parsedBody = $parser->parse((string) $this->body);
137-
}
138-
139-
if (
140-
null === $this->parsedBody
141-
|| is_array($this->parsedBody)
142-
|| is_object($this->parsedBody)
143-
) {
144-
$request = $request->withParsedBody($this->parsedBody);
145-
}
146-
147-
if (! $isBodyEmpty) {
148-
$request = $request->withBody($this->body);
149-
}
150-
151-
if (! empty($this->uploadedFiles)) {
152-
$request = $request->withUploadedFiles($this->uploadedFiles);
153-
}
154-
155-
return $request;
113+
return $this->request;
156114
}
157115

158116
public function addMethod(): self
159117
{
160-
$this->method = (empty($this->server['REQUEST_METHOD']))
161-
? 'GET'
162-
: $this->server['REQUEST_METHOD'];
118+
if (! empty($this->server['REQUEST_METHOD'])) {
119+
$this->request = $this->request->withMethod($this->server['REQUEST_METHOD']);
120+
}
163121

164122
return $this;
165123
}
166124

167125
public function addUri(): self
168126
{
169-
$server = $this->server;
170-
171-
$uriParts = parse_url($server['REQUEST_URI'] ?? '');
172-
[$path, $query, $fragment] = $this->extractUriComponents($server, $uriParts);
127+
$uriParts = parse_url($this->server['REQUEST_URI'] ?? '');
128+
[$path, $query, $fragment] = $this->extractUriComponents($this->server, $uriParts);
173129

174130
$baseUri = $this->getUriAuthorityWithScheme();
175131

176132
if ($path) {
177133
$baseUri = rtrim($baseUri, '/') . '/' . ltrim($path, '/');
178134
}
179135

180-
$this->uri = (
136+
$uri = (
181137
($baseUri ?: '/')
182138
. ($query ? ('?' . ltrim($query, '?')) : '')
183139
. ($fragment ? "#{$fragment}" : '')
184140
);
185141

142+
parse_str($query, $queryParams);
143+
144+
$this->request = $this->request
145+
->withUri($this->factory->createUri($uri))
146+
->withQueryParams($queryParams);
147+
186148
return $this;
187149
}
188150

@@ -193,22 +155,26 @@ public function addUri(): self
193155
*/
194156
public function addProtocolVersion(): self
195157
{
158+
$protocolVer = '1.1';
159+
196160
if (
197161
isset($this->server['SERVER_PROTOCOL'])
198-
&& $this->server['SERVER_PROTOCOL'] !== "HTTP/{$this->protocolVer}"
162+
&& $this->server['SERVER_PROTOCOL'] !== "HTTP/{$protocolVer}"
199163
) {
200-
$this->protocolVer = strtr((string) $this->server['SERVER_PROTOCOL'], ['HTTP/' => '']);
164+
$protocolVer = strtr((string) $this->server['SERVER_PROTOCOL'], ['HTTP/' => '']);
201165

202-
$isNumeric = (int) $this->protocolVer;
166+
$isNumeric = (int) $protocolVer;
203167

204168
if (! $isNumeric) {
205169
throw new UnexpectedValueException(sprintf(
206170
'Unrecognized protocol version "%s"',
207-
$this->protocolVer
171+
$protocolVer
208172
));
209173
}
210174
}
211175

176+
$this->request = $this->request->withProtocolVersion($protocolVer);
177+
212178
return $this;
213179
}
214180

@@ -222,10 +188,27 @@ public function addHeaders(): self
222188
$str = strtolower(str_replace('_', '-', $str));
223189
preg_match_all($pattern, $str, $normalizedHeaders, PREG_SET_ORDER);
224190

225-
$this->headers = [
226-
'original' => $originalHeaders,
227-
'normalized' => $normalizedHeaders,
228-
];
191+
$totalMatches = count($normalizedHeaders);
192+
193+
for ($i = 0; $i < $totalMatches; $i++) {
194+
$isRedirect = ! (empty($normalizedHeaders[$i][1]));
195+
$originalKey = $originalHeaders[$i][2] . $originalHeaders[$i][3];
196+
197+
// apache prefixes environment variables with `REDIRECT_` if they are
198+
// added by rewrite rules
199+
if ($isRedirect) {
200+
if (isset($this->server[$originalKey])) {
201+
continue;
202+
}
203+
204+
$originalKey = 'REDIRECT_' . $originalKey;
205+
}
206+
207+
$newKey = $normalizedHeaders[$i][2] . $normalizedHeaders[$i][3];
208+
209+
$this->request = $this->request
210+
->withHeader($newKey, $this->server[$originalKey]);
211+
}
229212

230213
return $this;
231214
}
@@ -236,7 +219,8 @@ public function addCookieParams(array $cookies): self
236219
$cookies = $this->parseCookieHeader($this->server['HTTP_COOKIE']);
237220
}
238221

239-
$this->cookieParams = $cookies ?: $this->cookieParams;
222+
$this->request = $this->request
223+
->withCookieParams($cookies ?: []);
240224

241225
return $this;
242226
}
@@ -254,7 +238,11 @@ public function addParsedBody($parsedBody): self
254238
);
255239
}
256240

241+
$this->request = $this->request
242+
->withParsedBody($parsedBody);
243+
257244
$this->parsedBody = $parsedBody;
245+
258246
return $this;
259247
}
260248

@@ -274,6 +262,7 @@ public function addBody($body): self
274262
}
275263

276264
if ($body instanceof StreamInterface && (string) $body !== '') {
265+
$this->request = $this->request->withBody($body);
277266
$this->body = $body;
278267
}
279268

@@ -292,7 +281,8 @@ public function addBody($body): self
292281
*/
293282
public function addUploadedFiles(array $files): self
294283
{
295-
$this->uploadedFiles = self::normalizeUploadedFiles($files, $this->factory);
284+
$this->request = $this->request
285+
->withUploadedFiles($this->normalizeUploadedFiles($files));
296286

297287
return $this;
298288
}
@@ -305,33 +295,32 @@ public function addUploadedFiles(array $files): self
305295
* instances.
306296
*
307297
* @param array $files `$_FILES` struct.
308-
* @param UploadedFileFactoryInterface|StreamFactoryInterface $httpFactory
309298
*
310299
* @return UploadedFileInterface[]|UploadedFileInterface
311300
*/
312-
private static function createUploadedFileFromSpec(array $files, $httpFactory)
301+
private function createUploadedFileFromSpec(array $files)
313302
{
314303
if (is_array($files['tmp_name'])) {
315304
$normalizedFiles = [];
316305

317306
foreach ($files['tmp_name'] as $key => $file) {
318-
$normalizedFiles[$key] = self::createUploadedFileFromSpec([
307+
$normalizedFiles[$key] = $this->createUploadedFileFromSpec([
319308
'tmp_name' => $files['tmp_name'][$key],
320309
'size' => $files['size'][$key],
321310
'error' => $files['error'][$key],
322311
'name' => $files['name'][$key],
323312
'type' => $files['type'][$key],
324-
], $httpFactory);
313+
]);
325314
}
326315

327316
return $normalizedFiles;
328317
}
329318

330319
$stream = ($files['tmp_name'] instanceof StreamInterface)
331320
? $files['tmp_name']
332-
: $httpFactory->createStreamFromFile($files['tmp_name'], 'r+');
321+
: $this->factory->createStreamFromFile($files['tmp_name'], 'r+');
333322

334-
return $httpFactory->createUploadedFile(
323+
return $this->factory->createUploadedFile(
335324
$stream,
336325
$files['size'],
337326
(int) $files['error'],
@@ -345,13 +334,12 @@ private static function createUploadedFileFromSpec(array $files, $httpFactory)
345334
* arrays are normalized.
346335
*
347336
* @param array $files
348-
* @param UploadedFileFactoryInterface|StreamFactoryInterface $httpFactory
349337
*
350338
* @return UploadedFileInterface[]
351339
*
352340
* @throws InvalidArgumentException
353341
*/
354-
private static function normalizeUploadedFiles(array $files, $httpFactory): array
342+
private function normalizeUploadedFiles(array $files): array
355343
{
356344
$normalized = [];
357345

@@ -363,8 +351,8 @@ private static function normalizeUploadedFiles(array $files, $httpFactory): arra
363351

364352
if (is_array($value)) {
365353
$normalized[$key] = (isset($value['tmp_name']))
366-
? self::createUploadedFileFromSpec($value, $httpFactory)
367-
: self::normalizeUploadedFiles($value, $httpFactory);
354+
? $this->createUploadedFileFromSpec($value)
355+
: $this->normalizeUploadedFiles($value);
368356
continue;
369357
}
370358

@@ -436,35 +424,6 @@ private function parseCookieHeader(string $cookieHeader): array
436424
return $cookies;
437425
}
438426

439-
private function addHeadersToServerRequest(
440-
ServerRequestInterface $request
441-
): ServerRequestInterface {
442-
$originalHeaders = $this->headers['original'];
443-
$normalizedHeaders = $this->headers['normalized'];
444-
$totalMatches = count($normalizedHeaders);
445-
446-
for ($i = 0; $i < $totalMatches; $i++) {
447-
$isRedirect = ! (empty($normalizedHeaders[$i][1]));
448-
$originalKey = $originalHeaders[$i][2] . $originalHeaders[$i][3];
449-
450-
// apache prefixes environment variables with `REDIRECT_` if they are
451-
// added by rewrite rules
452-
if ($isRedirect) {
453-
if (isset($this->server[$originalKey])) {
454-
continue;
455-
}
456-
457-
$originalKey = 'REDIRECT_' . $originalKey;
458-
}
459-
460-
$newKey = $normalizedHeaders[$i][2] . $normalizedHeaders[$i][3];
461-
462-
$request = $request->withHeader($newKey, $this->server[$originalKey]);
463-
}
464-
465-
return $request;
466-
}
467-
468427
private function extractUriComponents(array $server, array $uriParts): array
469428
{
470429
$path = '';
@@ -485,8 +444,6 @@ private function extractUriComponents(array $server, array $uriParts): array
485444
$query = $uriParts['query'];
486445
}
487446

488-
parse_str($query, $this->queryParams);
489-
490447
$fragment = (! empty($uriParts['fragment'])) ? $uriParts['fragment'] : '';
491448
return [$path, $query, $fragment];
492449
}

0 commit comments

Comments
 (0)