react-http2/src/Http2Middleware.php

64 lines
1.7 KiB
PHP

<?php
namespace NoccyLabs\React\Http2;
use NoccyLabs\React\Http2\Connection\Http2Connection;
use NoccyLabs\React\Http2\Frame\SettingsFrame;
use Psr\Http\Message\ServerRequestInterface;
use React\Stream\DuplexResourceStream;
use React\Stream\DuplexStreamInterface;
use React\Stream\ThroughStream;
use SplObjectStorage;
class Http2Middleware
{
/** @var SplObjectStorage<Http2Connection> Active connections */
private SplObjectStorage $connections;
public function __construct()
{
$this->connections = new SplObjectStorage();
}
public function __invoke(ServerRequestInterface $request, ?callable $next=null)
{
// expect upgrade h2 for secure connections, h2c for plaintext
// TODO handle HTTP/2 upgrade from HTTP/1.1
// TODO handle HTTP/2 with prior knowledge
}
/**
* Parse the settings frame present in the HTTP/1.1 upgrade request.
*
* @param string $settings
* @return SettingsFrame
*/
private function parseSettingsFromBase64String(string $settings): SettingsFrame
{
$decoded = base64_decode($settings);
$frame = new SettingsFrame();
$frame->fromBinary($decoded);
return $frame;
}
/**
* Prepare a connection for the HTTP/2 session.
*
* @param ServerRequestInterface $request
* @return Http2Connection
*/
private function setupConnection(ServerRequestInterface $request): Http2Connection
{
$stream = new ThroughStream();
$connection = new Http2Connection($stream);
$this->connections->attach($connection);
$connection->on('close', function () use ($connection) {
$this->connections->detach($connection);
});
return $connection;
}
}