Skip to content

[HttpClient][Contracts] add HttpClient\ApiClientInterface et al. #30414

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
140 changes: 140 additions & 0 deletions src/Symfony/Component/HttpClient/ApiClient.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,140 @@
<?php

/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/

namespace Symfony\Component\HttpClient;

use Symfony\Component\HttpClient\Response\ApiResponse;
use Symfony\Component\HttpClient\Response\ResponseIterator;
use Symfony\Contracts\HttpClient\ApiClientInterface;
use Symfony\Contracts\HttpClient\HttpClientInterface;
use Symfony\Contracts\HttpClient\ResponseInterface;
use Symfony\Contracts\HttpClient\ResponseIteratorInterface;

/**
* ApiClient helps to interact with common HTTP APIs.
*
* When responses need to be streamed, an HttpClientInterface implementation should be used instead.
*
* @author Nicolas Grekas <p@tchwork.com>
*/
final class ApiClient implements ApiClientInterface
{
use HttpClientTrait;

private $client;
private $defaultOptions = [
'headers' => [
'accept' => ['application/json'],
],
] + ApiClientInterface::OPTIONS_DEFAULTS;

/**
* A factory to instantiate the best possible API client for the runtime.
*
* @param array $defaultOptions Default requests' options
* @param int $maxHostConnections The maximum number of connections to a single host
*
* @see HttpClientInterface::OPTIONS_DEFAULTS for available options
*/
public static function create(array $defaultOptions = [], int $maxHostConnections = 6): ApiClientInterface
{
return new self(HttpClient::create($defaultOptions, $maxHostConnections));
}

public function __construct(HttpClientInterface $client, array $defaultOptions = [])
{
$this->client = $client;

if ($defaultOptions) {
[, $this->defaultOptions] = self::prepareRequest(null, null, $defaultOptions, $this->defaultOptions);
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

would it be possible to refactor the HttpClientTrait to have separate methods for the url and the options? i see that one section of the trait prepareRequest uses null === $url as a flag to do auth or not. i think this could be refactored too, to be more explicit and to have an options resolution that is not preparing the request.

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

That's not completely possible as there is some coupling between options and url - the most obvious example is the base_uri options. I'd be happy to review a PR if you want to work on one.

}
}

/**
* {@inheritdoc}
*/
public function get(string $url, array $options = []): ResponseInterface
{
return $this->requestApi('GET', $url, $options);
}

/**
* {@inheritdoc}
*/
public function head(string $url, array $options = []): ResponseInterface
{
return $this->requestApi('HEAD', $url, $options);
}

/**
* {@inheritdoc}
*/
public function post(string $url, array $options = []): ResponseInterface
{
return $this->requestApi('POST', $url, $options);
}

/**
* {@inheritdoc}
*/
public function put(string $url, array $options = []): ResponseInterface
{
return $this->requestApi('PUT', $url, $options);
}

/**
* {@inheritdoc}
*/
public function patch(string $url, array $options = []): ResponseInterface
{
return $this->requestApi('PATCH', $url, $options);
}

/**
* {@inheritdoc}
*/
public function delete(string $url, array $options = []): ResponseInterface
{
return $this->requestApi('DELETE', $url, $options);
}

/**
* {@inheritdoc}
*/
public function options(string $url, array $options = []): ResponseInterface
{
return $this->requestApi('OPTIONS', $url, $options);
}

/**
* {@inheritdoc}
*
* @param ApiResponse|ApiResponse[] $responses
*/
public function complete($responses, float $timeout = null): ResponseIteratorInterface
{
if ($responses instanceof ApiResponse) {
$responses = [$responses];
} elseif (!\is_iterable($responses)) {
throw new \TypeError(sprintf('%s() expects parameter 1 to be iterable of ApiResponse objects, %s given.', __METHOD__, \is_object($responses) ? \get_class($responses) : \gettype($responses)));
}

return new ResponseIterator(ApiResponse::complete($this->client, $responses, $timeout));
}

private function requestApi(string $method, string $url, array $options): ApiResponse
{
$options['buffer'] = true;
[, $options] = self::prepareRequest(null, null, $options, $this->defaultOptions);

return new ApiResponse($this->client->request($method, $url, $options));
}
}
148 changes: 148 additions & 0 deletions src/Symfony/Component/HttpClient/Response/ApiResponse.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,148 @@
<?php

/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/

namespace Symfony\Component\HttpClient\Response;

use Symfony\Component\HttpClient\Exception\TransportException;
use Symfony\Contracts\HttpClient\Exception\TransportExceptionInterface;
use Symfony\Contracts\HttpClient\HttpClientInterface;
use Symfony\Contracts\HttpClient\ResponseInterface;

/**
* @author Nicolas Grekas <p@tchwork.com>
*
* @internal
*/
final class ApiResponse implements ResponseInterface
{
private $response;
private $data;
private $error;
private $timeout;

/**
* @internal
*/
public function __construct(ResponseInterface $response)
{
$this->response = $response;
}

/**
* {@inheritdoc}
*/
public function getStatusCode(): int
{
$this->clearError();

return $this->response->getStatusCode();
}

/**
* {@inheritdoc}
*/
public function getHeaders(bool $throw = true): array
{
$this->clearError();

return $this->response->getHeaders($throw);
}

/**
* {@inheritdoc}
*/
public function getContent(bool $throw = true): string
{
$this->clearError();

return $this->response->getContent($throw);
}

/**
* {@inheritdoc}
*/
public function getInfo(string $type = null)
{
return $this->response->getInfo($type);
}

/**
* {@inheritdoc}
*/
public function toArray(bool $throw = true): array
{
$this->clearError();

return $this->response->toArray($throw);
}

public function __destruct()
{
if ($this->timeout) {
throw new TransportException('API response reached the inactivity timeout.');
}

$this->clearError();
}

private function clearError()
{
$e = $this->error;
$this->timeout = $this->error = null;

if ($e) {
throw new TransportException($e->getMessage(), 0, $e);
}
}

/**
* @param self[] $apiResponses
*
* @internal
*/
public static function complete(HttpClientInterface $client, iterable $apiResponses, ?float $timeout): \Generator
{
$responses = new \SplObjectStorage();

foreach ($apiResponses as $k => $r) {
if (!$r instanceof self) {
throw new \TypeError(sprintf('ApiClient::complete() expects parameter $responses to be iterable of ApiResponse objects, %s given.', __METHOD__, \is_object($r) ? \get_class($r) : \gettype($r)));
}

$responses[$r->response] = [$k, $r];
}
$apiResponses = null;

foreach ($client->stream($responses, $timeout) as $response => $chunk) {
[$k, $r] = $responses[$response];

try {
// Skip timed out responses but throw on destruct if unchecked
$r->timeout = $chunk->isTimeout();

if ($r->timeout || !$chunk->isLast()) {
continue;
}
} catch (TransportExceptionInterface $e) {
// Ensure errors are always thrown, last resort on destruct
$r->error = $e;
// Ensure PHP can clear memory as early as possible
$e = null;
}

unset($responses[$response]);

yield $k => $r;

$r->clearError();
}
}
}
55 changes: 55 additions & 0 deletions src/Symfony/Component/HttpClient/Response/ResponseIterator.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
<?php

/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/

namespace Symfony\Component\HttpClient\Response;

use Symfony\Contracts\HttpClient\ResponseInterface;
use Symfony\Contracts\HttpClient\ResponseIteratorInterface;

/**
* @author Nicolas Grekas <p@tchwork.com>
*
* @internal
*/
final class ResponseIterator implements ResponseIteratorInterface
{
private $generator;

public function __construct(\Generator $generator)
{
$this->generator = $generator;
}

public function key()
{
return $this->generator->key();
}

public function current(): ResponseInterface
{
return $this->generator->current();
}

public function next(): void
{
$this->generator->next();
}

public function rewind(): void
{
$this->generator->rewind();
}

public function valid(): bool
{
return $this->generator->valid();
}
}
28 changes: 28 additions & 0 deletions src/Symfony/Component/HttpClient/Tests/CurlApiClientTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
<?php

/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/

namespace Symfony\Component\HttpClient\Tests;

use Symfony\Component\HttpClient\ApiClient;
use Symfony\Component\HttpClient\CurlHttpClient;
use Symfony\Contracts\HttpClient\ApiClientInterface;
use Symfony\Contracts\HttpClient\Test\ApiClientTestCase;

/**
* @requires extension curl
*/
class CurlApiClientTest extends ApiClientTestCase
{
protected function getApiClient(): ApiClientInterface
{
return new ApiClient(new CurlHttpClient());
}
}
Loading