Skip to content

Commit

Permalink
Add adapter for PSR-18 compatible client
Browse files Browse the repository at this point in the history
  • Loading branch information
voronkovich committed Sep 4, 2021
1 parent b34ff1e commit 9b59b57
Showing 1 changed file with 66 additions and 0 deletions.
66 changes: 66 additions & 0 deletions src/HttpClient/Psr18Adapter.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
<?php

declare(strict_types=1);

namespace Voronkovich\SberbankAcquiring\HttpClient;

use Psr\Http\Client\ClientInterface;
use Psr\Http\Message\RequestFactoryInterface;
use Psr\Http\Message\StreamFactoryInterface;

/**
* Adapter for the PSR-18 compatible HTTP client.
*
* @author Oleg Voronkovich <[email protected]>
* @see https://www.php-fig.org/psr/psr-18/
*/
class Psr18Adapter implements HttpClientInterface
{
private $client;
private $requestFactory;
private $streamFactory;

public function __construct(ClientInterface $client, RequestFactoryInterface $requestFactory, StreamFactoryInterface $streamFactory)
{
$this->client = $client;
$this->requestFactory = $requestFactory;
$this->streamFactory = $streamFactory;
}

public function request(string $uri, string $method = HttpClientInterface::METHOD_GET, array $headers = [], string $data = ''): array
{
switch ($method) {
case HttpClientInterface::METHOD_GET:
$request = $this->requestFactory->createRequest('GET', $uri . '?' . $data);
break;
case HttpClientInterface::METHOD_POST:
$request = $this->requestFactory->createRequest('POST', $uri);

$body = $this->streamFactory->createStream($data);

$request = $request->withBody($body);
break;
default:
throw new \InvalidArgumentException(
sprintf(
'Invalid HTTP method "%s". Use "%s" or "%s".',
$method,
HttpClientInterface::METHOD_GET,
HttpClientInterface::METHOD_POST
)
);
break;
}

foreach ($headers as $key => $value) {
$request = $request->withHeader($key, $value);
}

$response = $this->client->sendRequest($request);

$statusCode = $response->getStatusCode();
$body = (string) $response->getBody();

return [$statusCode, $body];
}
}

0 comments on commit 9b59b57

Please sign in to comment.