Skip to content

Instantly share code, notes, and snippets.

@hacktivista
Last active March 29, 2019 21:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hacktivista/63cdd322e3764793f7885efdf91da76a to your computer and use it in GitHub Desktop.
Save hacktivista/63cdd322e3764793f7885efdf91da76a to your computer and use it in GitHub Desktop.
PSR-7-17-18 HttpClient
<?php
namespace Omnipay\Common;
use Http\Discovery\Psr17FactoryDiscovery;
use Http\Discovery\Psr18ClientDiscovery;
use Psr\Http\Message\RequestFactoryInterface;
use Psr\Http\Message\StreamFactoryInterface;
use Psr\Http\Message\UriFactoryInterface;
use Psr\Http\Message\RequestInterface;
use Psr\Http\Message\StreamInterface;
use Psr\Http\Message\UriInterface;
use Psr\Http\Client\ClientInterface;
class HttpClient implements (
ClientInterface, RequestFactoryInterface, StreamFactoryInterface,
UriFactoryInterface
) {
/**
* @var ClientInterface
*/
private $client;
/**
* @var RequestFactoryInterface
*/
private $requestFactory;
/**
* @var StreamFactoryInterface
*/
private $streamFactory;
/**
* @var UriFactoryInterface
*/
private $uriFactory;
public function __construct(
ClientInterface $client = null,
RequestFactoryInterface $requestFactory = null,
StreamFactoryInterface $streamFactory = null,
UriFactoryInterface $uriFactory = null
) {
$this->client = $client;
$this->requestFactory = $requestFactory;
$this->streamFactory = $streamFactory;
$this->uriFactory = $uriFactory;
}
/**
* DRY factory getter
* Loads a factory into memory only if requested
*
* @param $propertyName camelCased property name
* @return factory set in constructor, otherwise the discovered by default
*/
private function getFactory(string $propertyName)
{
if (empty($this->{$propertyName})) {
$this->{$propertyName} = Psr17FactoryDiscovery::{'find' . ucfirst($propertyName)}();
}
return $this->{$propertyName};
}
protected function getClient(): ClientInterface
{
if (empty($this->client)) {
$this->client = Psr18ClientDiscovery::find();
}
return $this->client;
}
protected function getRequestFactory(): RequestFactoryInterface
{
return $this->getFactory('requestFactory');
}
protected function getStreamFactory(): StreamFactoryInterface
{
return $this->getFactory('streamFactory');
}
protected function getUriFactory(): UriFactoryInterface
{
return $this->getFactory('uriFactory');
}
public function createRequest(string $method, $uri): RequestInterface
{
return $this->getRequestFactory()->createRequest($method, $uri);
}
public function createStream(string $content): StreamInterface
{
return $this->getStreamFactory()->createStream($content);
}
public function createUri(string $uri): UriInterface
{
return $this->getUriFactory()->createUri($uri);
}
public function sendRequest(RequestInterface $request): RequestInterface
{
return $this->getClient()->sendRequest($request);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment