From d41cfb1be27dfd50b43d6d44ccc0ce97b2483cf5 Mon Sep 17 00:00:00 2001 From: Christopher Vagnetoft Date: Thu, 25 Jul 2024 14:41:21 +0200 Subject: [PATCH] Header parsing improvements * Made headers public readonly in HeadersFrame * Fetching headers by value implemented * Initial tests for HeaderBag --- src/Frame/HeadersFrame.php | 19 +++++++++++++++++++ src/Header/HeaderBag.php | 18 +++++++++++++++++- tests/Header/HeaderBagTest.php | 33 +++++++++++++++++++++++++++++++++ 3 files changed, 69 insertions(+), 1 deletion(-) create mode 100644 tests/Header/HeaderBagTest.php diff --git a/src/Frame/HeadersFrame.php b/src/Frame/HeadersFrame.php index e3f0e9d..db67798 100644 --- a/src/Frame/HeadersFrame.php +++ b/src/Frame/HeadersFrame.php @@ -2,7 +2,26 @@ namespace NoccyLabs\React\Http2\Frame; +use NoccyLabs\React\Http2\Header\HeaderBag; +use NoccyLabs\React\Http2\Header\HeaderPacker; + class HeadersFrame extends Frame { + static ?HeaderPacker $headerPacker = null; + + public readonly HeaderBag $headers; + + public function fromBinary(string $binary): void + { + if (!self::$headerPacker) + self::$headerPacker = new HeaderPacker(); + + $this->headers = self::$headerPacker->unpackHeaders($binary); + } + + public function toBinary(): string + { + return self::$headerPacker->packHeaders($this->headers); + } } diff --git a/src/Header/HeaderBag.php b/src/Header/HeaderBag.php index 6cf9ced..707c7e2 100644 --- a/src/Header/HeaderBag.php +++ b/src/Header/HeaderBag.php @@ -25,7 +25,23 @@ class HeaderBag implements IteratorAggregate public function append(string $name, string $value) { - $this->headers[] = [ $name, $value ]; + $this->headers[] = [$name, $value ]; + } + + public function getAllHeaders(): array + { + return $this->headers; + } + + public function getHeaders(string $name): ?array + { + return array_map(fn($v) => $v[1], array_filter($this->headers, fn($v) => $v[0] == $name)); + } + + public function getHeaderLine(string $name): ?string + { + $headers = $this->getHeaders($name); + return array_shift($headers); } public function getIterator(): Traversable diff --git a/tests/Header/HeaderBagTest.php b/tests/Header/HeaderBagTest.php new file mode 100644 index 0000000..bcceb9b --- /dev/null +++ b/tests/Header/HeaderBagTest.php @@ -0,0 +1,33 @@ + 'GET', + ':scheme' => 'http', + ':path' => '/', + ':authority' => 'www.example.com' + ]); + $out = $packer->unpackHeaders($in); + + $this->assertEquals('GET', $out->getHeaderLine(':method')); + $this->assertEquals('http', $out->getHeaderLine(':scheme')); + $this->assertEquals('/', $out->getHeaderLine(':path')); + $this->assertEquals('www.example.com', $out->getHeaderLine(':authority')); + + } + + +}