Skip to content

Commit

Permalink
Re-write protocol version 2.0 to 2
Browse files Browse the repository at this point in the history
Fixes #15.
  • Loading branch information
trowski committed Nov 10, 2024
1 parent 6c7589a commit 394f2c5
Showing 1 changed file with 20 additions and 4 deletions.
24 changes: 20 additions & 4 deletions src/PsrAdapter.php
Original file line number Diff line number Diff line change
Expand Up @@ -9,11 +9,15 @@
use Amp\Http\Client\Request;
use Amp\Http\Client\Response;
use Psr\Http\Client\ClientExceptionInterface;
use Psr\Http\Message\MessageInterface as PsrMessage;
use Psr\Http\Message\RequestFactoryInterface as PsrRequestFactory;
use Psr\Http\Message\RequestInterface as PsrRequest;
use Psr\Http\Message\ResponseFactoryInterface as PsrResponseFactory;
use Psr\Http\Message\ResponseInterface as PsrResponse;

/**
* @psalm-import-type ProtocolVersion from Request
*/
final class PsrAdapter
{
public function __construct(
Expand All @@ -27,18 +31,16 @@ public function fromPsrRequest(PsrRequest $source): Request
/** @psalm-suppress ArgumentTypeCoercion Wrong typehints in PSR */
$target = new Request($source->getUri(), $source->getMethod());
$target->setHeaders($source->getHeaders());
/** @psalm-suppress ArgumentTypeCoercion Wrong typehints in PSR */
$target->setProtocolVersions([$source->getProtocolVersion()]);
$target->setProtocolVersions([$this->getProtocolVersion($source)]);
$target->setBody(new PsrStreamBody($source->getBody()));

return $target;
}

public function fromPsrResponse(PsrResponse $source, Request $request, ?Response $previousResponse = null): Response
{
/** @psalm-suppress ArgumentTypeCoercion Wrong typehints in PSR */
return new Response(
$source->getProtocolVersion(),
$this->getProtocolVersion($source),
$source->getStatusCode(),
$source->getReasonPhrase(),
$source->getHeaders(),
Expand Down Expand Up @@ -113,4 +115,18 @@ private function toPsrRequestWithoutBody(

return $target;
}

/**
* @return ProtocolVersion
*/
private function getProtocolVersion(PsrMessage $source): string
{
$protocolVersion = $source->getProtocolVersion();

return match ($protocolVersion) {
'2.0' => '2',
'2', '1.1', '1.0' => $protocolVersion,
default => throw new \Error('Invalid protocol version: ' . $protocolVersion),
};
}
}

0 comments on commit 394f2c5

Please sign in to comment.