Skip to content

Commit 8392ffb

Browse files
committed
HeaderParserTrait
1 parent 98804ef commit 8392ffb

File tree

2 files changed

+42
-13
lines changed

2 files changed

+42
-13
lines changed
Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
<?php declare(strict_types=1);
2+
3+
namespace VerifierServer\Endpoints;
4+
5+
/**
6+
* Trait HeaderParserTrait
7+
*
8+
* Provides functionality to parse HTTP request headers from a raw HTTP request string.
9+
*
10+
* @package VerifierServer\Endpoints
11+
*/
12+
trait HeaderParserTrait
13+
{
14+
/**
15+
* Parses the headers from a raw HTTP request string.
16+
*
17+
* This method takes a raw HTTP request string, splits it into lines,
18+
* and extracts headers in the format "Header-Name: Header-Value".
19+
* It returns an associative array where the keys are header names
20+
* and the values are the corresponding header values.
21+
*
22+
* @param string $request The raw HTTP request string to parse.
23+
* @return array An associative array of headers, where the keys are
24+
* header names and the values are header values.
25+
*/
26+
static function parseHeaders(string $request): array
27+
{
28+
return array_reduce(
29+
explode(PHP_EOL, $request), fn($carry, $line) =>
30+
(strpos($line, ':') !== false)
31+
? $carry += [trim(strtok($line, ':')) => trim(substr($line, strpos($line, ':') + 1))]
32+
: $carry,
33+
[]);
34+
}
35+
}

src/VerifierServer/Endpoints/VerifiedEndpoint.php

Lines changed: 7 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -46,6 +46,7 @@
4646
*/
4747
class VerifiedEndpoint implements EndpointInterface
4848
{
49+
use HeaderParserTrait;
4950
public function __construct(private PersistentState &$state)
5051
{}
5152

@@ -119,19 +120,12 @@ private function get(int|string &$response, array &$content_type, string &$body)
119120
*/
120121
private function post(ServerRequestInterface|string $request, int|string &$response, array &$content_type, string &$body, bool $bypass_token = false): void
121122
{
122-
if ($request instanceof ServerRequestInterface) {
123-
$formData = $request->getHeaders();
124-
} elseif (is_string($request)) {
125-
$formData = [];
126-
$lines = explode(PHP_EOL, $request);
127-
foreach ($lines as $line) {
128-
if (strpos($line, ':') !== false) {
129-
[$key, $value] = explode(':', $line, 2);
130-
$formData[trim($key)] = trim($value);
131-
}
132-
}
133-
}
134-
123+
$formData = $request instanceof ServerRequestInterface
124+
? $request->getHeaders()
125+
: (is_string($request)
126+
? self::parseHeaders($request)
127+
: []);
128+
135129
$methodType = isset($formData['method'])
136130
? strtolower(trim(is_array($formData['method']) ? $formData['method'][0] : $formData['method']))
137131
: null;

0 commit comments

Comments
 (0)