Subir proyecto
This commit is contained in:
+72
@@ -0,0 +1,72 @@
|
||||
<?php
|
||||
|
||||
declare (strict_types=1);
|
||||
namespace WordPress\AiClient\Providers\Http\Abstracts;
|
||||
|
||||
use WordPress\AiClientDependencies\Http\Discovery\Psr18ClientDiscovery;
|
||||
use WordPress\AiClientDependencies\Http\Discovery\Strategy\DiscoveryStrategy;
|
||||
use WordPress\AiClientDependencies\Nyholm\Psr7\Factory\Psr17Factory;
|
||||
use WordPress\AiClientDependencies\Psr\Http\Client\ClientInterface;
|
||||
/**
|
||||
* Abstract discovery strategy for HTTP client implementations.
|
||||
*
|
||||
* Provides a base for registering custom HTTP client implementations
|
||||
* with HTTPlug's discovery mechanism. Subclasses must implement
|
||||
* the createClient() method to provide their specific PSR-18
|
||||
* HTTP client instance using the provided Psr17Factory.
|
||||
*
|
||||
* @since 1.1.0
|
||||
*/
|
||||
abstract class AbstractClientDiscoveryStrategy implements DiscoveryStrategy
|
||||
{
|
||||
/**
|
||||
* Initializes and registers the discovery strategy.
|
||||
*
|
||||
* @since 1.1.0
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public static function init(): void
|
||||
{
|
||||
if (!class_exists('WordPress\AiClientDependencies\Http\Discovery\Psr18ClientDiscovery')) {
|
||||
return;
|
||||
}
|
||||
Psr18ClientDiscovery::prependStrategy(static::class);
|
||||
}
|
||||
/**
|
||||
* {@inheritDoc}
|
||||
*
|
||||
* @since 1.1.0
|
||||
*
|
||||
* @param string $type The type of discovery.
|
||||
* @return array<array<string, mixed>> The discovery candidates.
|
||||
*/
|
||||
public static function getCandidates($type)
|
||||
{
|
||||
if (ClientInterface::class === $type) {
|
||||
return [['class' => static function () {
|
||||
$psr17Factory = new Psr17Factory();
|
||||
return static::createClient($psr17Factory);
|
||||
}]];
|
||||
}
|
||||
$psr17Factories = ['WordPress\AiClientDependencies\Psr\Http\Message\RequestFactoryInterface', 'WordPress\AiClientDependencies\Psr\Http\Message\ResponseFactoryInterface', 'WordPress\AiClientDependencies\Psr\Http\Message\ServerRequestFactoryInterface', 'WordPress\AiClientDependencies\Psr\Http\Message\StreamFactoryInterface', 'WordPress\AiClientDependencies\Psr\Http\Message\UploadedFileFactoryInterface', 'WordPress\AiClientDependencies\Psr\Http\Message\UriFactoryInterface'];
|
||||
if (in_array($type, $psr17Factories, \true)) {
|
||||
return [['class' => Psr17Factory::class]];
|
||||
}
|
||||
return [];
|
||||
}
|
||||
/**
|
||||
* Creates an instance of the HTTP client.
|
||||
*
|
||||
* Subclasses must implement this method to return their specific
|
||||
* PSR-18 HTTP client instance. The provided Psr17Factory implements
|
||||
* all PSR-17 interfaces (RequestFactory, ResponseFactory, StreamFactory,
|
||||
* etc.) and can be used to satisfy client constructor dependencies.
|
||||
*
|
||||
* @since 1.1.0
|
||||
*
|
||||
* @param Psr17Factory $psr17Factory The PSR-17 factory for creating HTTP messages.
|
||||
* @return ClientInterface The PSR-18 HTTP client.
|
||||
*/
|
||||
abstract protected static function createClient(Psr17Factory $psr17Factory): ClientInterface;
|
||||
}
|
||||
@@ -0,0 +1,134 @@
|
||||
<?php
|
||||
|
||||
declare (strict_types=1);
|
||||
namespace WordPress\AiClient\Providers\Http\Collections;
|
||||
|
||||
/**
|
||||
* Simple collection for managing HTTP headers with case-insensitive access.
|
||||
*
|
||||
* This class stores HTTP headers while preserving their original casing
|
||||
* and provides efficient case-insensitive lookups.
|
||||
*
|
||||
* @since 0.1.0
|
||||
*/
|
||||
class HeadersCollection
|
||||
{
|
||||
/**
|
||||
* @var array<string, list<string>> The headers with original casing.
|
||||
*/
|
||||
private array $headers = [];
|
||||
/**
|
||||
* @var array<string, string> Map of lowercase header names to actual header names.
|
||||
*/
|
||||
private array $headersMap = [];
|
||||
/**
|
||||
* Constructor.
|
||||
*
|
||||
* @since 0.1.0
|
||||
*
|
||||
* @param array<string, string|list<string>> $headers Initial headers.
|
||||
*/
|
||||
public function __construct(array $headers = [])
|
||||
{
|
||||
foreach ($headers as $name => $value) {
|
||||
$this->set($name, $value);
|
||||
}
|
||||
}
|
||||
/**
|
||||
* Gets a specific header value.
|
||||
*
|
||||
* @since 0.1.0
|
||||
*
|
||||
* @param string $name The header name (case-insensitive).
|
||||
* @return list<string>|null The header value(s) or null if not found.
|
||||
*/
|
||||
public function get(string $name): ?array
|
||||
{
|
||||
$lowerName = strtolower($name);
|
||||
if (!isset($this->headersMap[$lowerName])) {
|
||||
return null;
|
||||
}
|
||||
$actualName = $this->headersMap[$lowerName];
|
||||
return $this->headers[$actualName];
|
||||
}
|
||||
/**
|
||||
* Gets all headers.
|
||||
*
|
||||
* @since 0.1.0
|
||||
*
|
||||
* @return array<string, list<string>> All headers with their original casing.
|
||||
*/
|
||||
public function getAll(): array
|
||||
{
|
||||
return $this->headers;
|
||||
}
|
||||
/**
|
||||
* Gets header values as a comma-separated string.
|
||||
*
|
||||
* @since 0.1.0
|
||||
*
|
||||
* @param string $name The header name (case-insensitive).
|
||||
* @return string|null The header values as a comma-separated string or null if not found.
|
||||
*/
|
||||
public function getAsString(string $name): ?string
|
||||
{
|
||||
$values = $this->get($name);
|
||||
return $values !== null ? implode(', ', $values) : null;
|
||||
}
|
||||
/**
|
||||
* Checks if a header exists.
|
||||
*
|
||||
* @since 0.1.0
|
||||
*
|
||||
* @param string $name The header name (case-insensitive).
|
||||
* @return bool True if the header exists, false otherwise.
|
||||
*/
|
||||
public function has(string $name): bool
|
||||
{
|
||||
return isset($this->headersMap[strtolower($name)]);
|
||||
}
|
||||
/**
|
||||
* Sets a header value, replacing any existing value.
|
||||
*
|
||||
* @since 0.1.0
|
||||
*
|
||||
* @param string $name The header name.
|
||||
* @param string|list<string> $value The header value(s).
|
||||
* @return void
|
||||
*/
|
||||
private function set(string $name, $value): void
|
||||
{
|
||||
if (is_array($value)) {
|
||||
$normalizedValues = array_values($value);
|
||||
} else {
|
||||
// Split comma-separated string into array
|
||||
$normalizedValues = array_map('trim', explode(',', $value));
|
||||
}
|
||||
$lowerName = strtolower($name);
|
||||
// If header exists with different casing, remove the old casing
|
||||
if (isset($this->headersMap[$lowerName])) {
|
||||
$oldName = $this->headersMap[$lowerName];
|
||||
if ($oldName !== $name) {
|
||||
unset($this->headers[$oldName]);
|
||||
}
|
||||
}
|
||||
// Always use the new casing
|
||||
$this->headers[$name] = $normalizedValues;
|
||||
$this->headersMap[$lowerName] = $name;
|
||||
}
|
||||
/**
|
||||
* Returns a new instance with the specified header.
|
||||
*
|
||||
* @since 0.1.0
|
||||
*
|
||||
* @param string $name The header name.
|
||||
* @param string|list<string> $value The header value(s).
|
||||
* @return self A new instance with the header.
|
||||
*/
|
||||
public function withHeader(string $name, $value): self
|
||||
{
|
||||
$new = clone $this;
|
||||
$new->set($name, $value);
|
||||
return $new;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
<?php
|
||||
|
||||
declare (strict_types=1);
|
||||
namespace WordPress\AiClient\Providers\Http\Contracts;
|
||||
|
||||
use WordPress\AiClientDependencies\Psr\Http\Message\RequestInterface;
|
||||
use WordPress\AiClientDependencies\Psr\Http\Message\ResponseInterface;
|
||||
use WordPress\AiClient\Providers\Http\DTO\RequestOptions;
|
||||
/**
|
||||
* Interface for HTTP clients that support per-request transport options.
|
||||
*
|
||||
* Extends the capabilities of PSR-18 clients by allowing custom transport
|
||||
* configuration such as timeouts and redirect handling on each request.
|
||||
*
|
||||
* @since 0.2.0
|
||||
*/
|
||||
interface ClientWithOptionsInterface
|
||||
{
|
||||
/**
|
||||
* Sends an HTTP request with the given transport options.
|
||||
*
|
||||
* @since 0.2.0
|
||||
*
|
||||
* @param RequestInterface $request The PSR-7 request to send.
|
||||
* @param RequestOptions $options The request transport options. Must not be null.
|
||||
* @return ResponseInterface The PSR-7 response received.
|
||||
*/
|
||||
public function sendRequestWithOptions(RequestInterface $request, RequestOptions $options): ResponseInterface;
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
<?php
|
||||
|
||||
declare (strict_types=1);
|
||||
namespace WordPress\AiClient\Providers\Http\Contracts;
|
||||
|
||||
use WordPress\AiClient\Providers\Http\DTO\Request;
|
||||
use WordPress\AiClient\Providers\Http\DTO\RequestOptions;
|
||||
use WordPress\AiClient\Providers\Http\DTO\Response;
|
||||
/**
|
||||
* Interface for HTTP transport implementations.
|
||||
*
|
||||
* Handles sending HTTP requests and receiving responses using
|
||||
* PSR-7, PSR-17, and PSR-18 standards internally.
|
||||
*
|
||||
* @since 0.1.0
|
||||
*/
|
||||
interface HttpTransporterInterface
|
||||
{
|
||||
/**
|
||||
* Sends an HTTP request and returns the response.
|
||||
*
|
||||
* @since 0.1.0
|
||||
*
|
||||
* @param Request $request The request to send.
|
||||
* @param RequestOptions|null $options Optional transport options for the request.
|
||||
* @return Response The response received.
|
||||
*/
|
||||
public function send(Request $request, ?RequestOptions $options = null): Response;
|
||||
}
|
||||
+24
@@ -0,0 +1,24 @@
|
||||
<?php
|
||||
|
||||
declare (strict_types=1);
|
||||
namespace WordPress\AiClient\Providers\Http\Contracts;
|
||||
|
||||
use WordPress\AiClient\Common\Contracts\WithJsonSchemaInterface;
|
||||
use WordPress\AiClient\Providers\Http\DTO\Request;
|
||||
/**
|
||||
* Interface for HTTP request authentication.
|
||||
*
|
||||
* @since 0.1.0
|
||||
*/
|
||||
interface RequestAuthenticationInterface extends WithJsonSchemaInterface
|
||||
{
|
||||
/**
|
||||
* Authenticates an HTTP request.
|
||||
*
|
||||
* @since 0.1.0
|
||||
*
|
||||
* @param Request $request The request to authenticate.
|
||||
* @return Request The authenticated request.
|
||||
*/
|
||||
public function authenticateRequest(Request $request): Request;
|
||||
}
|
||||
+30
@@ -0,0 +1,30 @@
|
||||
<?php
|
||||
|
||||
declare (strict_types=1);
|
||||
namespace WordPress\AiClient\Providers\Http\Contracts;
|
||||
|
||||
/**
|
||||
* Interface for models that require HTTP transport capabilities.
|
||||
*
|
||||
* @since 0.1.0
|
||||
*/
|
||||
interface WithHttpTransporterInterface
|
||||
{
|
||||
/**
|
||||
* Sets the HTTP transporter.
|
||||
*
|
||||
* @since 0.1.0
|
||||
*
|
||||
* @param HttpTransporterInterface $transporter The HTTP transporter instance.
|
||||
* @return void
|
||||
*/
|
||||
public function setHttpTransporter(\WordPress\AiClient\Providers\Http\Contracts\HttpTransporterInterface $transporter): void;
|
||||
/**
|
||||
* Returns the HTTP transporter.
|
||||
*
|
||||
* @since 0.1.0
|
||||
*
|
||||
* @return HttpTransporterInterface The HTTP transporter instance.
|
||||
*/
|
||||
public function getHttpTransporter(): \WordPress\AiClient\Providers\Http\Contracts\HttpTransporterInterface;
|
||||
}
|
||||
+30
@@ -0,0 +1,30 @@
|
||||
<?php
|
||||
|
||||
declare (strict_types=1);
|
||||
namespace WordPress\AiClient\Providers\Http\Contracts;
|
||||
|
||||
/**
|
||||
* Interface for models that support request authentication.
|
||||
*
|
||||
* @since 0.1.0
|
||||
*/
|
||||
interface WithRequestAuthenticationInterface
|
||||
{
|
||||
/**
|
||||
* Sets the request authentication.
|
||||
*
|
||||
* @since 0.1.0
|
||||
*
|
||||
* @param RequestAuthenticationInterface $authentication The authentication instance.
|
||||
* @return void
|
||||
*/
|
||||
public function setRequestAuthentication(\WordPress\AiClient\Providers\Http\Contracts\RequestAuthenticationInterface $authentication): void;
|
||||
/**
|
||||
* Returns the request authentication.
|
||||
*
|
||||
* @since 0.1.0
|
||||
*
|
||||
* @return RequestAuthenticationInterface The authentication instance.
|
||||
*/
|
||||
public function getRequestAuthentication(): \WordPress\AiClient\Providers\Http\Contracts\RequestAuthenticationInterface;
|
||||
}
|
||||
@@ -0,0 +1,92 @@
|
||||
<?php
|
||||
|
||||
declare (strict_types=1);
|
||||
namespace WordPress\AiClient\Providers\Http\DTO;
|
||||
|
||||
use WordPress\AiClient\Common\AbstractDataTransferObject;
|
||||
use WordPress\AiClient\Providers\Http\Contracts\RequestAuthenticationInterface;
|
||||
/**
|
||||
* Class for HTTP request authentication using an API key.
|
||||
*
|
||||
* @since 0.1.0
|
||||
*
|
||||
* @phpstan-type ApiKeyRequestAuthenticationArrayShape array{
|
||||
* apiKey: string
|
||||
* }
|
||||
*
|
||||
* @extends AbstractDataTransferObject<ApiKeyRequestAuthenticationArrayShape>
|
||||
*/
|
||||
class ApiKeyRequestAuthentication extends AbstractDataTransferObject implements RequestAuthenticationInterface
|
||||
{
|
||||
public const KEY_API_KEY = 'apiKey';
|
||||
/**
|
||||
* @var string The API key used for authentication.
|
||||
*/
|
||||
protected string $apiKey;
|
||||
/**
|
||||
* Constructor.
|
||||
*
|
||||
* @since 0.1.0
|
||||
*
|
||||
* @param string $apiKey The API key used for authentication.
|
||||
*/
|
||||
public function __construct(string $apiKey)
|
||||
{
|
||||
$this->apiKey = $apiKey;
|
||||
}
|
||||
/**
|
||||
* {@inheritDoc}
|
||||
*
|
||||
* @since 0.1.0
|
||||
*/
|
||||
public function authenticateRequest(\WordPress\AiClient\Providers\Http\DTO\Request $request): \WordPress\AiClient\Providers\Http\DTO\Request
|
||||
{
|
||||
// Add the API key to the request headers.
|
||||
return $request->withHeader('Authorization', 'Bearer ' . $this->apiKey);
|
||||
}
|
||||
/**
|
||||
* Gets the API key.
|
||||
*
|
||||
* @since 0.1.0
|
||||
*
|
||||
* @return string The API key.
|
||||
*/
|
||||
public function getApiKey(): string
|
||||
{
|
||||
return $this->apiKey;
|
||||
}
|
||||
/**
|
||||
* {@inheritDoc}
|
||||
*
|
||||
* @since 0.1.0
|
||||
*
|
||||
* @since 0.1.0
|
||||
*
|
||||
* @return ApiKeyRequestAuthenticationArrayShape
|
||||
*/
|
||||
public function toArray(): array
|
||||
{
|
||||
return [self::KEY_API_KEY => $this->apiKey];
|
||||
}
|
||||
/**
|
||||
* {@inheritDoc}
|
||||
*
|
||||
* @since 0.1.0
|
||||
*
|
||||
* @since 0.1.0
|
||||
*/
|
||||
public static function fromArray(array $array): self
|
||||
{
|
||||
static::validateFromArrayData($array, [self::KEY_API_KEY]);
|
||||
return new self($array[self::KEY_API_KEY]);
|
||||
}
|
||||
/**
|
||||
* {@inheritDoc}
|
||||
*
|
||||
* @since 0.1.0
|
||||
*/
|
||||
public static function getJsonSchema(): array
|
||||
{
|
||||
return ['type' => 'object', 'properties' => [self::KEY_API_KEY => ['type' => 'string', 'title' => 'API Key', 'description' => 'The API key used for authentication.']], 'required' => [self::KEY_API_KEY]];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,377 @@
|
||||
<?php
|
||||
|
||||
declare (strict_types=1);
|
||||
namespace WordPress\AiClient\Providers\Http\DTO;
|
||||
|
||||
use JsonException;
|
||||
use WordPress\AiClientDependencies\Psr\Http\Message\RequestInterface;
|
||||
use WordPress\AiClient\Common\AbstractDataTransferObject;
|
||||
use WordPress\AiClient\Common\Exception\InvalidArgumentException;
|
||||
use WordPress\AiClient\Providers\Http\Collections\HeadersCollection;
|
||||
use WordPress\AiClient\Providers\Http\Enums\HttpMethodEnum;
|
||||
/**
|
||||
* Represents an HTTP request.
|
||||
*
|
||||
* This class encapsulates HTTP request data that can be converted
|
||||
* to PSR-7 requests by the HTTP transporter.
|
||||
*
|
||||
* @since 0.1.0
|
||||
*
|
||||
* @phpstan-import-type RequestOptionsArrayShape from RequestOptions
|
||||
* @phpstan-type RequestArrayShape array{
|
||||
* method: string,
|
||||
* uri: string,
|
||||
* headers: array<string, list<string>>,
|
||||
* body?: string|null,
|
||||
* options?: RequestOptionsArrayShape
|
||||
* }
|
||||
*
|
||||
* @extends AbstractDataTransferObject<RequestArrayShape>
|
||||
*/
|
||||
class Request extends AbstractDataTransferObject
|
||||
{
|
||||
public const KEY_METHOD = 'method';
|
||||
public const KEY_URI = 'uri';
|
||||
public const KEY_HEADERS = 'headers';
|
||||
public const KEY_BODY = 'body';
|
||||
public const KEY_OPTIONS = 'options';
|
||||
/**
|
||||
* @var HttpMethodEnum The HTTP method.
|
||||
*/
|
||||
protected HttpMethodEnum $method;
|
||||
/**
|
||||
* @var string The request URI.
|
||||
*/
|
||||
protected string $uri;
|
||||
/**
|
||||
* @var HeadersCollection The request headers.
|
||||
*/
|
||||
protected HeadersCollection $headers;
|
||||
/**
|
||||
* @var array<string, mixed>|null The request data (for query params or form data).
|
||||
*/
|
||||
protected ?array $data = null;
|
||||
/**
|
||||
* @var string|null The request body (raw string content).
|
||||
*/
|
||||
protected ?string $body = null;
|
||||
/**
|
||||
* @var RequestOptions|null Request transport options.
|
||||
*/
|
||||
protected ?\WordPress\AiClient\Providers\Http\DTO\RequestOptions $options = null;
|
||||
/**
|
||||
* Constructor.
|
||||
*
|
||||
* @since 0.1.0
|
||||
*
|
||||
* @param HttpMethodEnum $method The HTTP method.
|
||||
* @param string $uri The request URI.
|
||||
* @param array<string, string|list<string>> $headers The request headers.
|
||||
* @param string|array<string, mixed>|null $data The request data.
|
||||
* @param RequestOptions|null $options The request transport options.
|
||||
*
|
||||
* @throws InvalidArgumentException If the URI is empty.
|
||||
*/
|
||||
public function __construct(HttpMethodEnum $method, string $uri, array $headers = [], $data = null, ?\WordPress\AiClient\Providers\Http\DTO\RequestOptions $options = null)
|
||||
{
|
||||
if (empty($uri)) {
|
||||
throw new InvalidArgumentException('URI cannot be empty.');
|
||||
}
|
||||
$this->method = $method;
|
||||
$this->uri = $uri;
|
||||
$this->headers = new HeadersCollection($headers);
|
||||
// Separate data and body based on type
|
||||
if (is_string($data)) {
|
||||
$this->body = $data;
|
||||
} elseif (is_array($data)) {
|
||||
$this->data = $data;
|
||||
}
|
||||
$this->options = $options;
|
||||
}
|
||||
/**
|
||||
* Creates a deep clone of this request.
|
||||
*
|
||||
* Clones the headers collection and request options to ensure
|
||||
* the cloned request is independent of the original.
|
||||
* The HTTP method enum is immutable and can be safely shared.
|
||||
*
|
||||
* @since 0.4.2
|
||||
*/
|
||||
public function __clone()
|
||||
{
|
||||
// Clone headers collection
|
||||
$this->headers = clone $this->headers;
|
||||
// Clone request options if present (contains only primitives)
|
||||
if ($this->options !== null) {
|
||||
$this->options = clone $this->options;
|
||||
}
|
||||
// Note: $method is an immutable enum and can be safely shared
|
||||
}
|
||||
/**
|
||||
* Gets the HTTP method.
|
||||
*
|
||||
* @since 0.1.0
|
||||
*
|
||||
* @return HttpMethodEnum The HTTP method.
|
||||
*/
|
||||
public function getMethod(): HttpMethodEnum
|
||||
{
|
||||
return $this->method;
|
||||
}
|
||||
/**
|
||||
* Gets the request URI.
|
||||
*
|
||||
* For GET requests with array data, appends the data as query parameters.
|
||||
*
|
||||
* @since 0.1.0
|
||||
*
|
||||
* @return string The URI.
|
||||
*/
|
||||
public function getUri(): string
|
||||
{
|
||||
// If GET request with data, append as query parameters
|
||||
if ($this->method === HttpMethodEnum::GET() && $this->data !== null && !empty($this->data)) {
|
||||
$separator = str_contains($this->uri, '?') ? '&' : '?';
|
||||
return $this->uri . $separator . http_build_query($this->data);
|
||||
}
|
||||
return $this->uri;
|
||||
}
|
||||
/**
|
||||
* Gets the request headers.
|
||||
*
|
||||
* @since 0.1.0
|
||||
*
|
||||
* @return array<string, list<string>> The headers.
|
||||
*/
|
||||
public function getHeaders(): array
|
||||
{
|
||||
return $this->headers->getAll();
|
||||
}
|
||||
/**
|
||||
* Gets a specific header value.
|
||||
*
|
||||
* @since 0.1.0
|
||||
*
|
||||
* @param string $name The header name (case-insensitive).
|
||||
* @return list<string>|null The header value(s) or null if not found.
|
||||
*/
|
||||
public function getHeader(string $name): ?array
|
||||
{
|
||||
return $this->headers->get($name);
|
||||
}
|
||||
/**
|
||||
* Gets header values as a comma-separated string.
|
||||
*
|
||||
* @since 0.1.0
|
||||
*
|
||||
* @param string $name The header name (case-insensitive).
|
||||
* @return string|null The header values as a comma-separated string, or null if not found.
|
||||
*/
|
||||
public function getHeaderAsString(string $name): ?string
|
||||
{
|
||||
return $this->headers->getAsString($name);
|
||||
}
|
||||
/**
|
||||
* Checks if a header exists.
|
||||
*
|
||||
* @since 0.1.0
|
||||
*
|
||||
* @param string $name The header name (case-insensitive).
|
||||
* @return bool True if the header exists, false otherwise.
|
||||
*/
|
||||
public function hasHeader(string $name): bool
|
||||
{
|
||||
return $this->headers->has($name);
|
||||
}
|
||||
/**
|
||||
* Gets the request body.
|
||||
*
|
||||
* For GET requests, returns null.
|
||||
* For POST/PUT/PATCH requests:
|
||||
* - If body is set, returns it as-is
|
||||
* - If data is set and Content-Type is JSON, returns JSON-encoded data
|
||||
* - If data is set and Content-Type is form, returns URL-encoded data
|
||||
*
|
||||
* @since 0.1.0
|
||||
*
|
||||
* @return string|null The body.
|
||||
* @throws JsonException If the data cannot be encoded to JSON.
|
||||
*/
|
||||
public function getBody(): ?string
|
||||
{
|
||||
// GET requests don't have a body
|
||||
if (!$this->method->hasBody()) {
|
||||
return null;
|
||||
}
|
||||
// If body is set, return it as-is
|
||||
if ($this->body !== null) {
|
||||
return $this->body;
|
||||
}
|
||||
// If data is set, encode based on content type
|
||||
if ($this->data !== null) {
|
||||
$contentType = $this->getContentType();
|
||||
// JSON encoding
|
||||
if ($contentType !== null && stripos($contentType, 'application/json') !== \false) {
|
||||
return json_encode($this->data, \JSON_THROW_ON_ERROR);
|
||||
}
|
||||
// Default to URL encoding for forms
|
||||
return http_build_query($this->data);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
/**
|
||||
* Gets the Content-Type header value.
|
||||
*
|
||||
* @since 0.1.0
|
||||
*
|
||||
* @return string|null The Content-Type header value or null if not set.
|
||||
*/
|
||||
private function getContentType(): ?string
|
||||
{
|
||||
$values = $this->getHeader('Content-Type');
|
||||
return $values !== null ? $values[0] : null;
|
||||
}
|
||||
/**
|
||||
* Returns a new instance with the specified header.
|
||||
*
|
||||
* @since 0.1.0
|
||||
*
|
||||
* @param string $name The header name.
|
||||
* @param string|list<string> $value The header value(s).
|
||||
* @return self A new instance with the header.
|
||||
*/
|
||||
public function withHeader(string $name, $value): self
|
||||
{
|
||||
$newHeaders = $this->headers->withHeader($name, $value);
|
||||
$new = clone $this;
|
||||
$new->headers = $newHeaders;
|
||||
return $new;
|
||||
}
|
||||
/**
|
||||
* Returns a new instance with the specified data.
|
||||
*
|
||||
* @since 0.1.0
|
||||
*
|
||||
* @param string|array<string, mixed> $data The request data.
|
||||
* @return self A new instance with the data.
|
||||
*/
|
||||
public function withData($data): self
|
||||
{
|
||||
$new = clone $this;
|
||||
if (is_string($data)) {
|
||||
$new->body = $data;
|
||||
$new->data = null;
|
||||
} elseif (is_array($data)) {
|
||||
$new->data = $data;
|
||||
$new->body = null;
|
||||
} else {
|
||||
$new->data = null;
|
||||
$new->body = null;
|
||||
}
|
||||
return $new;
|
||||
}
|
||||
/**
|
||||
* Gets the request data array.
|
||||
*
|
||||
* @since 0.1.0
|
||||
*
|
||||
* @return array<string, mixed>|null The request data array.
|
||||
*/
|
||||
public function getData(): ?array
|
||||
{
|
||||
return $this->data;
|
||||
}
|
||||
/**
|
||||
* Gets the request options.
|
||||
*
|
||||
* @since 0.2.0
|
||||
*
|
||||
* @return RequestOptions|null Request transport options when configured.
|
||||
*/
|
||||
public function getOptions(): ?\WordPress\AiClient\Providers\Http\DTO\RequestOptions
|
||||
{
|
||||
return $this->options;
|
||||
}
|
||||
/**
|
||||
* Returns a new instance with the specified request options.
|
||||
*
|
||||
* @since 0.2.0
|
||||
*
|
||||
* @param RequestOptions|null $options The request options to apply.
|
||||
* @return self A new instance with the options.
|
||||
*/
|
||||
public function withOptions(?\WordPress\AiClient\Providers\Http\DTO\RequestOptions $options): self
|
||||
{
|
||||
$new = clone $this;
|
||||
$new->options = $options;
|
||||
return $new;
|
||||
}
|
||||
/**
|
||||
* {@inheritDoc}
|
||||
*
|
||||
* @since 0.1.0
|
||||
*/
|
||||
public static function getJsonSchema(): array
|
||||
{
|
||||
return ['type' => 'object', 'properties' => [self::KEY_METHOD => ['type' => 'string', 'description' => 'The HTTP method.'], self::KEY_URI => ['type' => 'string', 'description' => 'The request URI.'], self::KEY_HEADERS => ['type' => 'object', 'additionalProperties' => ['type' => 'array', 'items' => ['type' => 'string']], 'description' => 'The request headers.'], self::KEY_BODY => ['type' => ['string'], 'description' => 'The request body.'], self::KEY_OPTIONS => \WordPress\AiClient\Providers\Http\DTO\RequestOptions::getJsonSchema()], 'required' => [self::KEY_METHOD, self::KEY_URI, self::KEY_HEADERS]];
|
||||
}
|
||||
/**
|
||||
* {@inheritDoc}
|
||||
*
|
||||
* @since 0.1.0
|
||||
*
|
||||
* @return RequestArrayShape
|
||||
*/
|
||||
public function toArray(): array
|
||||
{
|
||||
$array = [
|
||||
self::KEY_METHOD => $this->method->value,
|
||||
self::KEY_URI => $this->getUri(),
|
||||
// Include query params if GET with data
|
||||
self::KEY_HEADERS => $this->headers->getAll(),
|
||||
];
|
||||
// Include body if present (getBody() handles the conversion)
|
||||
$body = $this->getBody();
|
||||
if ($body !== null) {
|
||||
$array[self::KEY_BODY] = $body;
|
||||
}
|
||||
if ($this->options !== null) {
|
||||
$optionsArray = $this->options->toArray();
|
||||
if (!empty($optionsArray)) {
|
||||
$array[self::KEY_OPTIONS] = $optionsArray;
|
||||
}
|
||||
}
|
||||
return $array;
|
||||
}
|
||||
/**
|
||||
* {@inheritDoc}
|
||||
*
|
||||
* @since 0.1.0
|
||||
*/
|
||||
public static function fromArray(array $array): self
|
||||
{
|
||||
static::validateFromArrayData($array, [self::KEY_METHOD, self::KEY_URI, self::KEY_HEADERS]);
|
||||
return new self(HttpMethodEnum::from($array[self::KEY_METHOD]), $array[self::KEY_URI], $array[self::KEY_HEADERS] ?? [], $array[self::KEY_BODY] ?? null, isset($array[self::KEY_OPTIONS]) ? \WordPress\AiClient\Providers\Http\DTO\RequestOptions::fromArray($array[self::KEY_OPTIONS]) : null);
|
||||
}
|
||||
/**
|
||||
* Creates a Request instance from a PSR-7 RequestInterface.
|
||||
*
|
||||
* @since 0.2.0
|
||||
*
|
||||
* @param RequestInterface $psrRequest The PSR-7 request to convert.
|
||||
* @return self A new Request instance.
|
||||
* @throws InvalidArgumentException If the HTTP method is not supported.
|
||||
*/
|
||||
public static function fromPsrRequest(RequestInterface $psrRequest): self
|
||||
{
|
||||
$method = HttpMethodEnum::from($psrRequest->getMethod());
|
||||
$uri = (string) $psrRequest->getUri();
|
||||
// Convert PSR-7 headers to array format expected by our constructor
|
||||
/** @var array<string, list<string>> $headers */
|
||||
$headers = $psrRequest->getHeaders();
|
||||
// Get body content
|
||||
$body = $psrRequest->getBody()->getContents();
|
||||
$bodyOrData = !empty($body) ? $body : null;
|
||||
return new self($method, $uri, $headers, $bodyOrData);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,204 @@
|
||||
<?php
|
||||
|
||||
declare (strict_types=1);
|
||||
namespace WordPress\AiClient\Providers\Http\DTO;
|
||||
|
||||
use WordPress\AiClient\Common\AbstractDataTransferObject;
|
||||
use WordPress\AiClient\Common\Exception\InvalidArgumentException;
|
||||
/**
|
||||
* Represents optional HTTP transport configuration for a single request.
|
||||
*
|
||||
* Provides mutable setters for working with timeouts and redirect handling.
|
||||
*
|
||||
* @since 0.2.0
|
||||
*
|
||||
* @phpstan-type RequestOptionsArrayShape array{
|
||||
* timeout?: float|null,
|
||||
* connectTimeout?: float|null,
|
||||
* maxRedirects?: int|null
|
||||
* }
|
||||
*
|
||||
* @extends AbstractDataTransferObject<RequestOptionsArrayShape>
|
||||
*/
|
||||
class RequestOptions extends AbstractDataTransferObject
|
||||
{
|
||||
public const KEY_TIMEOUT = 'timeout';
|
||||
public const KEY_CONNECT_TIMEOUT = 'connectTimeout';
|
||||
public const KEY_MAX_REDIRECTS = 'maxRedirects';
|
||||
/**
|
||||
* @var float|null Maximum duration in seconds to wait for the full response.
|
||||
*/
|
||||
protected ?float $timeout = null;
|
||||
/**
|
||||
* @var float|null Maximum duration in seconds to wait for the initial connection.
|
||||
*/
|
||||
protected ?float $connectTimeout = null;
|
||||
/**
|
||||
* @var int|null Maximum number of redirects to follow. 0 disables redirects, null is unspecified.
|
||||
*/
|
||||
protected ?int $maxRedirects = null;
|
||||
/**
|
||||
* Sets the request timeout in seconds.
|
||||
*
|
||||
* @since 0.2.0
|
||||
*
|
||||
* @param float|null $timeout Timeout in seconds.
|
||||
* @return void
|
||||
*
|
||||
* @throws InvalidArgumentException When timeout is negative.
|
||||
*/
|
||||
public function setTimeout(?float $timeout): void
|
||||
{
|
||||
$this->validateTimeout($timeout, self::KEY_TIMEOUT);
|
||||
$this->timeout = $timeout;
|
||||
}
|
||||
/**
|
||||
* Sets the connection timeout in seconds.
|
||||
*
|
||||
* @since 0.2.0
|
||||
*
|
||||
* @param float|null $timeout Connection timeout in seconds.
|
||||
* @return void
|
||||
*
|
||||
* @throws InvalidArgumentException When timeout is negative.
|
||||
*/
|
||||
public function setConnectTimeout(?float $timeout): void
|
||||
{
|
||||
$this->validateTimeout($timeout, self::KEY_CONNECT_TIMEOUT);
|
||||
$this->connectTimeout = $timeout;
|
||||
}
|
||||
/**
|
||||
* Sets the maximum number of redirects to follow.
|
||||
*
|
||||
* Set to 0 to disable redirects, null for unspecified, or a positive integer
|
||||
* to enable redirects with a maximum count.
|
||||
*
|
||||
* @since 0.2.0
|
||||
*
|
||||
* @param int|null $maxRedirects Maximum redirects to follow, or 0 to disable, or null for unspecified.
|
||||
* @return void
|
||||
*
|
||||
* @throws InvalidArgumentException When redirect count is negative.
|
||||
*/
|
||||
public function setMaxRedirects(?int $maxRedirects): void
|
||||
{
|
||||
if ($maxRedirects !== null && $maxRedirects < 0) {
|
||||
throw new InvalidArgumentException('Request option "maxRedirects" must be greater than or equal to 0.');
|
||||
}
|
||||
$this->maxRedirects = $maxRedirects;
|
||||
}
|
||||
/**
|
||||
* Gets the request timeout in seconds.
|
||||
*
|
||||
* @since 0.2.0
|
||||
*
|
||||
* @return float|null Timeout in seconds.
|
||||
*/
|
||||
public function getTimeout(): ?float
|
||||
{
|
||||
return $this->timeout;
|
||||
}
|
||||
/**
|
||||
* Gets the connection timeout in seconds.
|
||||
*
|
||||
* @since 0.2.0
|
||||
*
|
||||
* @return float|null Connection timeout in seconds.
|
||||
*/
|
||||
public function getConnectTimeout(): ?float
|
||||
{
|
||||
return $this->connectTimeout;
|
||||
}
|
||||
/**
|
||||
* Checks whether redirects are allowed.
|
||||
*
|
||||
* @since 0.2.0
|
||||
*
|
||||
* @return bool|null True when redirects are allowed (maxRedirects > 0),
|
||||
* false when disabled (maxRedirects = 0),
|
||||
* null when unspecified (maxRedirects = null).
|
||||
*/
|
||||
public function allowsRedirects(): ?bool
|
||||
{
|
||||
if ($this->maxRedirects === null) {
|
||||
return null;
|
||||
}
|
||||
return $this->maxRedirects > 0;
|
||||
}
|
||||
/**
|
||||
* Gets the maximum number of redirects to follow.
|
||||
*
|
||||
* @since 0.2.0
|
||||
*
|
||||
* @return int|null Maximum redirects or null when not specified.
|
||||
*/
|
||||
public function getMaxRedirects(): ?int
|
||||
{
|
||||
return $this->maxRedirects;
|
||||
}
|
||||
/**
|
||||
* {@inheritDoc}
|
||||
*
|
||||
* @since 0.2.0
|
||||
*
|
||||
* @return RequestOptionsArrayShape
|
||||
*/
|
||||
public function toArray(): array
|
||||
{
|
||||
$data = [];
|
||||
if ($this->timeout !== null) {
|
||||
$data[self::KEY_TIMEOUT] = $this->timeout;
|
||||
}
|
||||
if ($this->connectTimeout !== null) {
|
||||
$data[self::KEY_CONNECT_TIMEOUT] = $this->connectTimeout;
|
||||
}
|
||||
if ($this->maxRedirects !== null) {
|
||||
$data[self::KEY_MAX_REDIRECTS] = $this->maxRedirects;
|
||||
}
|
||||
return $data;
|
||||
}
|
||||
/**
|
||||
* {@inheritDoc}
|
||||
*
|
||||
* @since 0.2.0
|
||||
*/
|
||||
public static function fromArray(array $array): self
|
||||
{
|
||||
$instance = new self();
|
||||
if (isset($array[self::KEY_TIMEOUT])) {
|
||||
$instance->setTimeout((float) $array[self::KEY_TIMEOUT]);
|
||||
}
|
||||
if (isset($array[self::KEY_CONNECT_TIMEOUT])) {
|
||||
$instance->setConnectTimeout((float) $array[self::KEY_CONNECT_TIMEOUT]);
|
||||
}
|
||||
if (isset($array[self::KEY_MAX_REDIRECTS])) {
|
||||
$instance->setMaxRedirects((int) $array[self::KEY_MAX_REDIRECTS]);
|
||||
}
|
||||
return $instance;
|
||||
}
|
||||
/**
|
||||
* {@inheritDoc}
|
||||
*
|
||||
* @since 0.2.0
|
||||
*/
|
||||
public static function getJsonSchema(): array
|
||||
{
|
||||
return ['type' => 'object', 'properties' => [self::KEY_TIMEOUT => ['type' => ['number', 'null'], 'minimum' => 0, 'description' => 'Maximum duration in seconds to wait for the full response.'], self::KEY_CONNECT_TIMEOUT => ['type' => ['number', 'null'], 'minimum' => 0, 'description' => 'Maximum duration in seconds to wait for the initial connection.'], self::KEY_MAX_REDIRECTS => ['type' => ['integer', 'null'], 'minimum' => 0, 'description' => 'Maximum redirects to follow. 0 disables, null is unspecified.']], 'additionalProperties' => \false];
|
||||
}
|
||||
/**
|
||||
* Validates timeout values.
|
||||
*
|
||||
* @since 0.2.0
|
||||
*
|
||||
* @param float|null $value Timeout to validate.
|
||||
* @param string $fieldName Field name for the error message.
|
||||
*
|
||||
* @throws InvalidArgumentException When timeout is negative.
|
||||
*/
|
||||
private function validateTimeout(?float $value, string $fieldName): void
|
||||
{
|
||||
if ($value !== null && $value < 0) {
|
||||
throw new InvalidArgumentException(sprintf('Request option "%s" must be greater than or equal to 0.', $fieldName));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,211 @@
|
||||
<?php
|
||||
|
||||
declare (strict_types=1);
|
||||
namespace WordPress\AiClient\Providers\Http\DTO;
|
||||
|
||||
use WordPress\AiClient\Common\AbstractDataTransferObject;
|
||||
use WordPress\AiClient\Common\Exception\InvalidArgumentException;
|
||||
use WordPress\AiClient\Providers\Http\Collections\HeadersCollection;
|
||||
/**
|
||||
* Represents an HTTP response.
|
||||
*
|
||||
* This class encapsulates HTTP response data that has been converted
|
||||
* from PSR-7 responses by the HTTP transporter.
|
||||
*
|
||||
* @since 0.1.0
|
||||
*
|
||||
* @phpstan-type ResponseArrayShape array{
|
||||
* statusCode: int,
|
||||
* headers: array<string, list<string>>,
|
||||
* body?: string|null
|
||||
* }
|
||||
*
|
||||
* @extends AbstractDataTransferObject<ResponseArrayShape>
|
||||
*/
|
||||
class Response extends AbstractDataTransferObject
|
||||
{
|
||||
public const KEY_STATUS_CODE = 'statusCode';
|
||||
public const KEY_HEADERS = 'headers';
|
||||
public const KEY_BODY = 'body';
|
||||
/**
|
||||
* @var int The HTTP status code.
|
||||
*/
|
||||
protected int $statusCode;
|
||||
/**
|
||||
* @var HeadersCollection The response headers.
|
||||
*/
|
||||
protected HeadersCollection $headers;
|
||||
/**
|
||||
* @var string|null The response body.
|
||||
*/
|
||||
protected ?string $body;
|
||||
/**
|
||||
* Constructor.
|
||||
*
|
||||
* @since 0.1.0
|
||||
*
|
||||
* @param int $statusCode The HTTP status code.
|
||||
* @param array<string, string|list<string>> $headers The response headers.
|
||||
* @param string|null $body The response body.
|
||||
*
|
||||
* @throws InvalidArgumentException If the status code is invalid.
|
||||
*/
|
||||
public function __construct(int $statusCode, array $headers, ?string $body = null)
|
||||
{
|
||||
if ($statusCode < 100 || $statusCode >= 600) {
|
||||
throw new InvalidArgumentException('Invalid HTTP status code: ' . $statusCode);
|
||||
}
|
||||
$this->statusCode = $statusCode;
|
||||
$this->headers = new HeadersCollection($headers);
|
||||
$this->body = $body;
|
||||
}
|
||||
/**
|
||||
* Creates a deep clone of this response.
|
||||
*
|
||||
* Clones the headers collection to ensure the cloned
|
||||
* response is independent of the original.
|
||||
*
|
||||
* @since 0.4.2
|
||||
*/
|
||||
public function __clone()
|
||||
{
|
||||
// Clone headers collection
|
||||
$this->headers = clone $this->headers;
|
||||
}
|
||||
/**
|
||||
* Gets the HTTP status code.
|
||||
*
|
||||
* @since 0.1.0
|
||||
*
|
||||
* @return int The status code.
|
||||
*/
|
||||
public function getStatusCode(): int
|
||||
{
|
||||
return $this->statusCode;
|
||||
}
|
||||
/**
|
||||
* Gets the response headers.
|
||||
*
|
||||
* @since 0.1.0
|
||||
*
|
||||
* @return array<string, list<string>> The headers.
|
||||
*/
|
||||
public function getHeaders(): array
|
||||
{
|
||||
return $this->headers->getAll();
|
||||
}
|
||||
/**
|
||||
* Gets a specific header value.
|
||||
*
|
||||
* @since 0.1.0
|
||||
*
|
||||
* @param string $name The header name (case-insensitive).
|
||||
* @return list<string>|null The header value(s) or null if not found.
|
||||
*/
|
||||
public function getHeader(string $name): ?array
|
||||
{
|
||||
return $this->headers->get($name);
|
||||
}
|
||||
/**
|
||||
* Gets header values as a comma-separated string.
|
||||
*
|
||||
* @since 0.1.0
|
||||
*
|
||||
* @param string $name The header name (case-insensitive).
|
||||
* @return string|null The header values as a comma-separated string or null if not found.
|
||||
*/
|
||||
public function getHeaderAsString(string $name): ?string
|
||||
{
|
||||
return $this->headers->getAsString($name);
|
||||
}
|
||||
/**
|
||||
* Gets the response body.
|
||||
*
|
||||
* @since 0.1.0
|
||||
*
|
||||
* @return string|null The body.
|
||||
*/
|
||||
public function getBody(): ?string
|
||||
{
|
||||
return $this->body;
|
||||
}
|
||||
/**
|
||||
* Checks if the response has a header.
|
||||
*
|
||||
* @since 0.1.0
|
||||
*
|
||||
* @param string $name The header name.
|
||||
* @return bool True if the header exists, false otherwise.
|
||||
*/
|
||||
public function hasHeader(string $name): bool
|
||||
{
|
||||
return $this->headers->has($name);
|
||||
}
|
||||
/**
|
||||
* Checks if the response indicates success.
|
||||
*
|
||||
* @since 0.1.0
|
||||
*
|
||||
* @return bool True if status code is 2xx, false otherwise.
|
||||
*/
|
||||
public function isSuccessful(): bool
|
||||
{
|
||||
return $this->statusCode >= 200 && $this->statusCode < 300;
|
||||
}
|
||||
/**
|
||||
* Gets the response data as an array.
|
||||
*
|
||||
* Attempts to decode the body as JSON. Returns null if the body
|
||||
* is empty or not valid JSON.
|
||||
*
|
||||
* @since 0.1.0
|
||||
*
|
||||
* @return array<string, mixed>|null The decoded data or null.
|
||||
*/
|
||||
public function getData(): ?array
|
||||
{
|
||||
if ($this->body === null || $this->body === '') {
|
||||
return null;
|
||||
}
|
||||
$data = json_decode($this->body, \true);
|
||||
if (json_last_error() !== \JSON_ERROR_NONE) {
|
||||
return null;
|
||||
}
|
||||
/** @var array<string, mixed>|null $data */
|
||||
return is_array($data) ? $data : null;
|
||||
}
|
||||
/**
|
||||
* {@inheritDoc}
|
||||
*
|
||||
* @since 0.1.0
|
||||
*/
|
||||
public static function getJsonSchema(): array
|
||||
{
|
||||
return ['type' => 'object', 'properties' => [self::KEY_STATUS_CODE => ['type' => 'integer', 'minimum' => 100, 'maximum' => 599, 'description' => 'The HTTP status code.'], self::KEY_HEADERS => ['type' => 'object', 'additionalProperties' => ['type' => 'array', 'items' => ['type' => 'string']], 'description' => 'The response headers.'], self::KEY_BODY => ['type' => ['string', 'null'], 'description' => 'The response body.']], 'required' => [self::KEY_STATUS_CODE, self::KEY_HEADERS]];
|
||||
}
|
||||
/**
|
||||
* {@inheritDoc}
|
||||
*
|
||||
* @since 0.1.0
|
||||
*
|
||||
* @return ResponseArrayShape
|
||||
*/
|
||||
public function toArray(): array
|
||||
{
|
||||
$data = [self::KEY_STATUS_CODE => $this->statusCode, self::KEY_HEADERS => $this->headers->getAll()];
|
||||
if ($this->body !== null) {
|
||||
$data[self::KEY_BODY] = $this->body;
|
||||
}
|
||||
return $data;
|
||||
}
|
||||
/**
|
||||
* {@inheritDoc}
|
||||
*
|
||||
* @since 0.1.0
|
||||
*/
|
||||
public static function fromArray(array $array): self
|
||||
{
|
||||
static::validateFromArrayData($array, [self::KEY_STATUS_CODE, self::KEY_HEADERS]);
|
||||
return new self($array[self::KEY_STATUS_CODE], $array[self::KEY_HEADERS], $array[self::KEY_BODY] ?? null);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,110 @@
|
||||
<?php
|
||||
|
||||
declare (strict_types=1);
|
||||
namespace WordPress\AiClient\Providers\Http\Enums;
|
||||
|
||||
use WordPress\AiClient\Common\AbstractEnum;
|
||||
/**
|
||||
* Represents HTTP request methods.
|
||||
*
|
||||
* @since 0.1.0
|
||||
*
|
||||
* @method static self GET()
|
||||
* @method static self POST()
|
||||
* @method static self PUT()
|
||||
* @method static self PATCH()
|
||||
* @method static self DELETE()
|
||||
* @method static self HEAD()
|
||||
* @method static self OPTIONS()
|
||||
* @method static self CONNECT()
|
||||
* @method static self TRACE()
|
||||
*
|
||||
* @method bool isGet()
|
||||
* @method bool isPost()
|
||||
* @method bool isPut()
|
||||
* @method bool isPatch()
|
||||
* @method bool isDelete()
|
||||
* @method bool isHead()
|
||||
* @method bool isOptions()
|
||||
* @method bool isConnect()
|
||||
* @method bool isTrace()
|
||||
*/
|
||||
final class HttpMethodEnum extends AbstractEnum
|
||||
{
|
||||
/**
|
||||
* GET method for retrieving resources.
|
||||
*
|
||||
* @var string
|
||||
*/
|
||||
public const GET = 'GET';
|
||||
/**
|
||||
* POST method for creating resources.
|
||||
*
|
||||
* @var string
|
||||
*/
|
||||
public const POST = 'POST';
|
||||
/**
|
||||
* PUT method for updating/replacing resources.
|
||||
*
|
||||
* @var string
|
||||
*/
|
||||
public const PUT = 'PUT';
|
||||
/**
|
||||
* PATCH method for partially updating resources.
|
||||
*
|
||||
* @var string
|
||||
*/
|
||||
public const PATCH = 'PATCH';
|
||||
/**
|
||||
* DELETE method for removing resources.
|
||||
*
|
||||
* @var string
|
||||
*/
|
||||
public const DELETE = 'DELETE';
|
||||
/**
|
||||
* HEAD method for retrieving headers only.
|
||||
*
|
||||
* @var string
|
||||
*/
|
||||
public const HEAD = 'HEAD';
|
||||
/**
|
||||
* OPTIONS method for retrieving allowed methods.
|
||||
*
|
||||
* @var string
|
||||
*/
|
||||
public const OPTIONS = 'OPTIONS';
|
||||
/**
|
||||
* CONNECT method for establishing tunnel.
|
||||
*
|
||||
* @var string
|
||||
*/
|
||||
public const CONNECT = 'CONNECT';
|
||||
/**
|
||||
* TRACE method for diagnostic purposes.
|
||||
*
|
||||
* @var string
|
||||
*/
|
||||
public const TRACE = 'TRACE';
|
||||
/**
|
||||
* Checks if this method is idempotent.
|
||||
*
|
||||
* @since 0.1.0
|
||||
*
|
||||
* @return bool True if the method is idempotent, false otherwise.
|
||||
*/
|
||||
public function isIdempotent(): bool
|
||||
{
|
||||
return in_array($this->value, [self::GET, self::HEAD, self::OPTIONS, self::TRACE, self::PUT, self::DELETE], \true);
|
||||
}
|
||||
/**
|
||||
* Checks if this method typically has a request body.
|
||||
*
|
||||
* @since 0.1.0
|
||||
*
|
||||
* @return bool True if the method typically has a body, false otherwise.
|
||||
*/
|
||||
public function hasBody(): bool
|
||||
{
|
||||
return in_array($this->value, [self::POST, self::PUT, self::PATCH], \true);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
<?php
|
||||
|
||||
declare (strict_types=1);
|
||||
namespace WordPress\AiClient\Providers\Http\Enums;
|
||||
|
||||
use WordPress\AiClient\Common\AbstractEnum;
|
||||
use WordPress\AiClient\Common\Contracts\WithArrayTransformationInterface;
|
||||
use WordPress\AiClient\Providers\Http\Contracts\RequestAuthenticationInterface;
|
||||
use WordPress\AiClient\Providers\Http\DTO\ApiKeyRequestAuthentication;
|
||||
/**
|
||||
* Enum for request authentication methods.
|
||||
*
|
||||
* @since 0.4.0
|
||||
*
|
||||
* @method static self apiKey() Creates an instance for API_KEY method.
|
||||
* @method bool isApiKey() Checks if the method is API_KEY.
|
||||
*/
|
||||
class RequestAuthenticationMethod extends AbstractEnum
|
||||
{
|
||||
/**
|
||||
* API key authentication.
|
||||
*/
|
||||
public const API_KEY = 'api_key';
|
||||
/**
|
||||
* Gets the implementation class for the authentication method.
|
||||
*
|
||||
* @since 0.4.0
|
||||
*
|
||||
* @return class-string<RequestAuthenticationInterface&WithArrayTransformationInterface> The implementation class.
|
||||
*
|
||||
* @phpstan-ignore missingType.generics
|
||||
*/
|
||||
public function getImplementationClass(): string
|
||||
{
|
||||
// At the moment, this is the only supported method.
|
||||
// Once more methods are available, add conditionals here for each method.
|
||||
return ApiKeyRequestAuthentication::class;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,68 @@
|
||||
<?php
|
||||
|
||||
declare (strict_types=1);
|
||||
namespace WordPress\AiClient\Providers\Http\Exception;
|
||||
|
||||
use WordPress\AiClient\Common\Exception\InvalidArgumentException;
|
||||
use WordPress\AiClient\Providers\Http\DTO\Request;
|
||||
use WordPress\AiClient\Providers\Http\DTO\Response;
|
||||
use WordPress\AiClient\Providers\Http\Util\ErrorMessageExtractor;
|
||||
/**
|
||||
* Exception thrown for 4xx HTTP client errors.
|
||||
*
|
||||
* This represents errors where the client request was malformed,
|
||||
* unauthorized, forbidden, or otherwise invalid.
|
||||
*
|
||||
* @since 0.2.0
|
||||
*/
|
||||
class ClientException extends InvalidArgumentException
|
||||
{
|
||||
/**
|
||||
* The request that failed.
|
||||
*
|
||||
* @var Request|null
|
||||
*/
|
||||
protected ?Request $request = null;
|
||||
/**
|
||||
* Returns the request that failed as our Request DTO.
|
||||
*
|
||||
* @since 0.2.0
|
||||
*
|
||||
* @return Request
|
||||
* @throws \RuntimeException If no request is available
|
||||
*/
|
||||
public function getRequest(): Request
|
||||
{
|
||||
if ($this->request === null) {
|
||||
throw new \RuntimeException('Request object not available. This exception was directly instantiated. ' . 'Use a factory method that provides request context.');
|
||||
}
|
||||
return $this->request;
|
||||
}
|
||||
/**
|
||||
* Creates a ClientException from a client error response (4xx).
|
||||
*
|
||||
* This method extracts error details from common API response formats
|
||||
* and creates an exception with a descriptive message and status code.
|
||||
*
|
||||
* @since 0.2.0
|
||||
*
|
||||
* @param Response $response The HTTP response that failed.
|
||||
* @return self
|
||||
*/
|
||||
public static function fromClientErrorResponse(Response $response): self
|
||||
{
|
||||
$statusCode = $response->getStatusCode();
|
||||
$statusTexts = [400 => 'Bad Request', 401 => 'Unauthorized', 403 => 'Forbidden', 404 => 'Not Found', 422 => 'Unprocessable Entity', 429 => 'Too Many Requests'];
|
||||
if (isset($statusTexts[$statusCode])) {
|
||||
$errorMessage = sprintf('%s (%d)', $statusTexts[$statusCode], $statusCode);
|
||||
} else {
|
||||
$errorMessage = sprintf('Client error (%d): Request was rejected due to client-side issue', $statusCode);
|
||||
}
|
||||
// Extract error message from response data using centralized utility
|
||||
$extractedError = ErrorMessageExtractor::extractFromResponseData($response->getData());
|
||||
if ($extractedError !== null) {
|
||||
$errorMessage .= ' - ' . $extractedError;
|
||||
}
|
||||
return new self($errorMessage, $statusCode);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,57 @@
|
||||
<?php
|
||||
|
||||
declare (strict_types=1);
|
||||
namespace WordPress\AiClient\Providers\Http\Exception;
|
||||
|
||||
use WordPress\AiClientDependencies\Psr\Http\Message\RequestInterface;
|
||||
use WordPress\AiClient\Common\Exception\RuntimeException;
|
||||
use WordPress\AiClient\Providers\Http\DTO\Request;
|
||||
/**
|
||||
* Exception thrown for network-related errors.
|
||||
*
|
||||
* This includes HTTP transport errors, connection failures,
|
||||
* timeouts, and other network-related issues.
|
||||
*
|
||||
* @since 0.2.0
|
||||
*/
|
||||
class NetworkException extends RuntimeException
|
||||
{
|
||||
/**
|
||||
* The request that failed.
|
||||
*
|
||||
* @var Request|null
|
||||
*/
|
||||
protected ?Request $request = null;
|
||||
/**
|
||||
* Returns the request that failed as our Request DTO.
|
||||
*
|
||||
* @since 0.2.0
|
||||
*
|
||||
* @return Request
|
||||
* @throws \RuntimeException If no request is available
|
||||
*/
|
||||
public function getRequest(): Request
|
||||
{
|
||||
if ($this->request === null) {
|
||||
throw new \RuntimeException('Request object not available. This exception was directly instantiated. ' . 'Use a factory method that provides request context.');
|
||||
}
|
||||
return $this->request;
|
||||
}
|
||||
/**
|
||||
* Creates a NetworkException from a PSR-18 network exception.
|
||||
*
|
||||
* @since 0.2.0
|
||||
*
|
||||
* @param RequestInterface $psrRequest The PSR-7 request that failed.
|
||||
* @param \Throwable $networkException The PSR-18 network exception.
|
||||
* @return self
|
||||
*/
|
||||
public static function fromPsr18NetworkException(RequestInterface $psrRequest, \Throwable $networkException): self
|
||||
{
|
||||
$request = Request::fromPsrRequest($psrRequest);
|
||||
$message = sprintf('Network error occurred while sending request to %s: %s', $request->getUri(), $networkException->getMessage());
|
||||
$exception = new self($message, 0, $networkException);
|
||||
$exception->request = $request;
|
||||
return $exception;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
<?php
|
||||
|
||||
declare (strict_types=1);
|
||||
namespace WordPress\AiClient\Providers\Http\Exception;
|
||||
|
||||
use WordPress\AiClient\Common\Exception\RuntimeException;
|
||||
use WordPress\AiClient\Providers\Http\DTO\Response;
|
||||
/**
|
||||
* Exception thrown for 3xx HTTP redirect responses.
|
||||
*
|
||||
* This represents cases where the server indicates that the request
|
||||
* should be retried at a different location, but automatic redirect
|
||||
* handling was not successful or not enabled.
|
||||
*
|
||||
* @since 0.2.0
|
||||
*/
|
||||
class RedirectException extends RuntimeException
|
||||
{
|
||||
/**
|
||||
* Creates a RedirectException from a redirect response.
|
||||
*
|
||||
* This method extracts redirect information from the response headers
|
||||
* and creates an exception with a descriptive message and status code.
|
||||
*
|
||||
* @since 0.2.0
|
||||
*
|
||||
* @param Response $response The HTTP redirect response.
|
||||
* @return self
|
||||
*/
|
||||
public static function fromRedirectResponse(Response $response): self
|
||||
{
|
||||
$statusCode = $response->getStatusCode();
|
||||
$statusTexts = [300 => 'Multiple Choices', 301 => 'Moved Permanently', 302 => 'Found', 303 => 'See Other', 304 => 'Not Modified', 307 => 'Temporary Redirect', 308 => 'Permanent Redirect'];
|
||||
if (isset($statusTexts[$statusCode])) {
|
||||
$errorMessage = sprintf('%s (%d)', $statusTexts[$statusCode], $statusCode);
|
||||
} else {
|
||||
$errorMessage = sprintf('Redirect error (%d): Request needs to be retried at a different location', $statusCode);
|
||||
}
|
||||
// Try to extract the redirect location from headers
|
||||
$locationValues = $response->getHeader('Location');
|
||||
if ($locationValues !== null && !empty($locationValues)) {
|
||||
$location = $locationValues[0];
|
||||
$errorMessage .= ' - Location: ' . $location;
|
||||
}
|
||||
return new self($errorMessage, $statusCode);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
<?php
|
||||
|
||||
declare (strict_types=1);
|
||||
namespace WordPress\AiClient\Providers\Http\Exception;
|
||||
|
||||
use WordPress\AiClient\Common\Exception\RuntimeException;
|
||||
/**
|
||||
* Exception class for HTTP response errors.
|
||||
*
|
||||
* This is used when response data is unexpected or malformed,
|
||||
* typically indicating that a provider changed in ways our code
|
||||
* is not aware of or when parsing response data fails.
|
||||
*
|
||||
* @since 0.1.0
|
||||
*/
|
||||
class ResponseException extends RuntimeException
|
||||
{
|
||||
/**
|
||||
* Creates a ResponseException for missing expected data.
|
||||
*
|
||||
* @since 0.2.0
|
||||
*
|
||||
* @param string $apiName The name of the API/provider.
|
||||
* @param string $fieldName The field that was expected but missing.
|
||||
* @return self
|
||||
*/
|
||||
public static function fromMissingData(string $apiName, string $fieldName): self
|
||||
{
|
||||
$message = sprintf('Unexpected %s API response: Missing the "%s" key.', $apiName, $fieldName);
|
||||
return new self($message);
|
||||
}
|
||||
/**
|
||||
* Creates a ResponseException from invalid data in an API response.
|
||||
*
|
||||
* @since 0.2.0
|
||||
*
|
||||
* @param string $apiName The name of the API service (e.g., 'OpenAI', 'Anthropic').
|
||||
* @param string $fieldName The field that was invalid.
|
||||
* @param string $message The specific error message describing the invalid data.
|
||||
* @return self
|
||||
*/
|
||||
public static function fromInvalidData(string $apiName, string $fieldName, string $message): self
|
||||
{
|
||||
return new self(sprintf('Unexpected %s API response: Invalid "%s" key: %s', $apiName, $fieldName, $message));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
<?php
|
||||
|
||||
declare (strict_types=1);
|
||||
namespace WordPress\AiClient\Providers\Http\Exception;
|
||||
|
||||
use WordPress\AiClient\Common\Exception\RuntimeException;
|
||||
use WordPress\AiClient\Providers\Http\DTO\Response;
|
||||
use WordPress\AiClient\Providers\Http\Util\ErrorMessageExtractor;
|
||||
/**
|
||||
* Exception thrown for 5xx HTTP server errors.
|
||||
*
|
||||
* This represents errors where the server failed to fulfill
|
||||
* a valid request due to internal server errors.
|
||||
*
|
||||
* @since 0.2.0
|
||||
*/
|
||||
class ServerException extends RuntimeException
|
||||
{
|
||||
/**
|
||||
* Creates a ServerException from a server error response.
|
||||
*
|
||||
* This method extracts error details from common API response formats
|
||||
* and creates an exception with a descriptive message and status code.
|
||||
*
|
||||
* @since 0.2.0
|
||||
*
|
||||
* @param Response $response The HTTP response that failed.
|
||||
* @return self
|
||||
*/
|
||||
public static function fromServerErrorResponse(Response $response): self
|
||||
{
|
||||
$statusCode = $response->getStatusCode();
|
||||
$statusTexts = [500 => 'Internal Server Error', 502 => 'Bad Gateway', 503 => 'Service Unavailable', 504 => 'Gateway Timeout', 507 => 'Insufficient Storage', 529 => 'Overloaded'];
|
||||
if (isset($statusTexts[$statusCode])) {
|
||||
$errorMessage = sprintf('%s (%d)', $statusTexts[$statusCode], $statusCode);
|
||||
} else {
|
||||
$errorMessage = sprintf('Server error (%d): Request was rejected due to server-side issue', $statusCode);
|
||||
}
|
||||
// Extract error message from response data using centralized utility
|
||||
$extractedError = ErrorMessageExtractor::extractFromResponseData($response->getData());
|
||||
if ($extractedError !== null) {
|
||||
$errorMessage .= ' - ' . $extractedError;
|
||||
}
|
||||
return new self($errorMessage, $response->getStatusCode());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,267 @@
|
||||
<?php
|
||||
|
||||
declare (strict_types=1);
|
||||
namespace WordPress\AiClient\Providers\Http;
|
||||
|
||||
use WordPress\AiClientDependencies\Http\Discovery\Psr17FactoryDiscovery;
|
||||
use WordPress\AiClientDependencies\Http\Discovery\Psr18ClientDiscovery;
|
||||
use WordPress\AiClientDependencies\Psr\Http\Client\ClientInterface;
|
||||
use WordPress\AiClientDependencies\Psr\Http\Message\RequestFactoryInterface;
|
||||
use WordPress\AiClientDependencies\Psr\Http\Message\RequestInterface;
|
||||
use WordPress\AiClientDependencies\Psr\Http\Message\ResponseInterface;
|
||||
use WordPress\AiClientDependencies\Psr\Http\Message\StreamFactoryInterface;
|
||||
use WordPress\AiClient\Common\Exception\RuntimeException;
|
||||
use WordPress\AiClient\Providers\Http\Contracts\ClientWithOptionsInterface;
|
||||
use WordPress\AiClient\Providers\Http\Contracts\HttpTransporterInterface;
|
||||
use WordPress\AiClient\Providers\Http\DTO\Request;
|
||||
use WordPress\AiClient\Providers\Http\DTO\RequestOptions;
|
||||
use WordPress\AiClient\Providers\Http\DTO\Response;
|
||||
use WordPress\AiClient\Providers\Http\Exception\NetworkException;
|
||||
/**
|
||||
* HTTP transporter implementation using HTTPlug.
|
||||
*
|
||||
* This class handles the conversion between custom Request/Response
|
||||
* objects and PSR-7 messages, using HTTPlug for client abstraction
|
||||
* and PSR-17 factories for message creation.
|
||||
*
|
||||
* @since 0.1.0
|
||||
*/
|
||||
class HttpTransporter implements HttpTransporterInterface
|
||||
{
|
||||
/**
|
||||
* @var RequestFactoryInterface PSR-17 request factory.
|
||||
*/
|
||||
private RequestFactoryInterface $requestFactory;
|
||||
/**
|
||||
* @var StreamFactoryInterface PSR-17 stream factory.
|
||||
*/
|
||||
private StreamFactoryInterface $streamFactory;
|
||||
/**
|
||||
* @var ClientInterface PSR-18 HTTP client.
|
||||
*/
|
||||
private ClientInterface $client;
|
||||
/**
|
||||
* Constructor.
|
||||
*
|
||||
* @since 0.1.0
|
||||
*
|
||||
* @param ClientInterface|null $client PSR-18 HTTP client.
|
||||
* @param RequestFactoryInterface|null $requestFactory PSR-17 request factory.
|
||||
* @param StreamFactoryInterface|null $streamFactory PSR-17 stream factory.
|
||||
*/
|
||||
public function __construct(?ClientInterface $client = null, ?RequestFactoryInterface $requestFactory = null, ?StreamFactoryInterface $streamFactory = null)
|
||||
{
|
||||
$this->client = $client ?: Psr18ClientDiscovery::find();
|
||||
$this->requestFactory = $requestFactory ?: Psr17FactoryDiscovery::findRequestFactory();
|
||||
$this->streamFactory = $streamFactory ?: Psr17FactoryDiscovery::findStreamFactory();
|
||||
}
|
||||
/**
|
||||
* {@inheritDoc}
|
||||
*
|
||||
* @since 0.1.0
|
||||
* @since 0.2.0 Added optional RequestOptions parameter and ClientWithOptions support.
|
||||
*/
|
||||
public function send(Request $request, ?RequestOptions $options = null): Response
|
||||
{
|
||||
$psr7Request = $this->convertToPsr7Request($request);
|
||||
// Merge request options with parameter options, with parameter options taking precedence
|
||||
$mergedOptions = $this->mergeOptions($request->getOptions(), $options);
|
||||
try {
|
||||
$hasOptions = $mergedOptions !== null;
|
||||
if ($hasOptions && $this->client instanceof ClientWithOptionsInterface) {
|
||||
$psr7Response = $this->client->sendRequestWithOptions($psr7Request, $mergedOptions);
|
||||
} elseif ($hasOptions && $this->isGuzzleClient($this->client)) {
|
||||
$psr7Response = $this->sendWithGuzzle($psr7Request, $mergedOptions);
|
||||
} else {
|
||||
$psr7Response = $this->client->sendRequest($psr7Request);
|
||||
}
|
||||
} catch (\WordPress\AiClientDependencies\Psr\Http\Client\NetworkExceptionInterface $e) {
|
||||
throw NetworkException::fromPsr18NetworkException($psr7Request, $e);
|
||||
} catch (\WordPress\AiClientDependencies\Psr\Http\Client\ClientExceptionInterface $e) {
|
||||
// Handle other PSR-18 client exceptions that are not network-related
|
||||
throw new RuntimeException(sprintf('HTTP client error occurred while sending request to %s: %s', $request->getUri(), $e->getMessage()), 0, $e);
|
||||
}
|
||||
return $this->convertFromPsr7Response($psr7Response);
|
||||
}
|
||||
/**
|
||||
* Merges request options with parameter options taking precedence.
|
||||
*
|
||||
* @since 0.2.0
|
||||
*
|
||||
* @param RequestOptions|null $requestOptions Options from the Request object.
|
||||
* @param RequestOptions|null $parameterOptions Options passed as method parameter.
|
||||
* @return RequestOptions|null Merged options, or null if both are null.
|
||||
*/
|
||||
private function mergeOptions(?RequestOptions $requestOptions, ?RequestOptions $parameterOptions): ?RequestOptions
|
||||
{
|
||||
// If no options at all, return null
|
||||
if ($requestOptions === null && $parameterOptions === null) {
|
||||
return null;
|
||||
}
|
||||
// If only one set of options exists, return it
|
||||
if ($requestOptions === null) {
|
||||
return $parameterOptions;
|
||||
}
|
||||
if ($parameterOptions === null) {
|
||||
return $requestOptions;
|
||||
}
|
||||
// Both exist, merge them with parameter options taking precedence
|
||||
$merged = new RequestOptions();
|
||||
// Start with request options (lower precedence)
|
||||
if ($requestOptions->getTimeout() !== null) {
|
||||
$merged->setTimeout($requestOptions->getTimeout());
|
||||
}
|
||||
if ($requestOptions->getConnectTimeout() !== null) {
|
||||
$merged->setConnectTimeout($requestOptions->getConnectTimeout());
|
||||
}
|
||||
if ($requestOptions->getMaxRedirects() !== null) {
|
||||
$merged->setMaxRedirects($requestOptions->getMaxRedirects());
|
||||
}
|
||||
// Override with parameter options (higher precedence)
|
||||
if ($parameterOptions->getTimeout() !== null) {
|
||||
$merged->setTimeout($parameterOptions->getTimeout());
|
||||
}
|
||||
if ($parameterOptions->getConnectTimeout() !== null) {
|
||||
$merged->setConnectTimeout($parameterOptions->getConnectTimeout());
|
||||
}
|
||||
if ($parameterOptions->getMaxRedirects() !== null) {
|
||||
$merged->setMaxRedirects($parameterOptions->getMaxRedirects());
|
||||
}
|
||||
return $merged;
|
||||
}
|
||||
/**
|
||||
* Determines if the underlying client matches the Guzzle client shape.
|
||||
*
|
||||
* @since 0.2.0
|
||||
*
|
||||
* @param ClientInterface $client The HTTP client instance.
|
||||
* @return bool True when the client exposes Guzzle's send signature.
|
||||
*/
|
||||
private function isGuzzleClient(ClientInterface $client): bool
|
||||
{
|
||||
$reflection = new \ReflectionObject($client);
|
||||
if (!is_callable([$client, 'send'])) {
|
||||
return \false;
|
||||
}
|
||||
if (!$reflection->hasMethod('send')) {
|
||||
return \false;
|
||||
}
|
||||
$method = $reflection->getMethod('send');
|
||||
if (!$method->isPublic() || $method->isStatic()) {
|
||||
return \false;
|
||||
}
|
||||
$parameters = $method->getParameters();
|
||||
if (count($parameters) < 2) {
|
||||
return \false;
|
||||
}
|
||||
$firstParameter = $parameters[0]->getType();
|
||||
if (!$firstParameter instanceof \ReflectionNamedType || $firstParameter->isBuiltin()) {
|
||||
return \false;
|
||||
}
|
||||
if (!is_a($firstParameter->getName(), RequestInterface::class, \true)) {
|
||||
return \false;
|
||||
}
|
||||
$secondParameter = $parameters[1];
|
||||
$secondType = $secondParameter->getType();
|
||||
if (!$secondType instanceof \ReflectionNamedType || $secondType->getName() !== 'array') {
|
||||
return \false;
|
||||
}
|
||||
return \true;
|
||||
}
|
||||
/**
|
||||
* Sends a request using a Guzzle-compatible client.
|
||||
*
|
||||
* @since 0.2.0
|
||||
*
|
||||
* @param RequestInterface $request The PSR-7 request to send.
|
||||
* @param RequestOptions $options The request options.
|
||||
* @return ResponseInterface The PSR-7 response received.
|
||||
*/
|
||||
private function sendWithGuzzle(RequestInterface $request, RequestOptions $options): ResponseInterface
|
||||
{
|
||||
$guzzleOptions = $this->buildGuzzleOptions($options);
|
||||
/** @var callable $callable */
|
||||
$callable = [$this->client, 'send'];
|
||||
/** @var ResponseInterface $response */
|
||||
$response = $callable($request, $guzzleOptions);
|
||||
return $response;
|
||||
}
|
||||
/**
|
||||
* Converts request options to a Guzzle-compatible options array.
|
||||
*
|
||||
* @since 0.2.0
|
||||
*
|
||||
* @param RequestOptions $options The request options.
|
||||
* @return array<string, mixed> Guzzle-compatible options.
|
||||
*/
|
||||
private function buildGuzzleOptions(RequestOptions $options): array
|
||||
{
|
||||
$guzzleOptions = [];
|
||||
$timeout = $options->getTimeout();
|
||||
if ($timeout !== null) {
|
||||
$guzzleOptions['timeout'] = $timeout;
|
||||
}
|
||||
$connectTimeout = $options->getConnectTimeout();
|
||||
if ($connectTimeout !== null) {
|
||||
$guzzleOptions['connect_timeout'] = $connectTimeout;
|
||||
}
|
||||
$allowRedirects = $options->allowsRedirects();
|
||||
if ($allowRedirects !== null) {
|
||||
if ($allowRedirects) {
|
||||
$redirectOptions = [];
|
||||
$maxRedirects = $options->getMaxRedirects();
|
||||
if ($maxRedirects !== null) {
|
||||
$redirectOptions['max'] = $maxRedirects;
|
||||
}
|
||||
$guzzleOptions['allow_redirects'] = !empty($redirectOptions) ? $redirectOptions : \true;
|
||||
} else {
|
||||
$guzzleOptions['allow_redirects'] = \false;
|
||||
}
|
||||
}
|
||||
return $guzzleOptions;
|
||||
}
|
||||
/**
|
||||
* Converts a custom Request to a PSR-7 request.
|
||||
*
|
||||
* @since 0.1.0
|
||||
*
|
||||
* @param Request $request The custom request.
|
||||
* @return RequestInterface The PSR-7 request.
|
||||
*/
|
||||
private function convertToPsr7Request(Request $request): RequestInterface
|
||||
{
|
||||
$psr7Request = $this->requestFactory->createRequest($request->getMethod()->value, $request->getUri());
|
||||
// Add headers
|
||||
foreach ($request->getHeaders() as $name => $values) {
|
||||
foreach ($values as $value) {
|
||||
$psr7Request = $psr7Request->withAddedHeader($name, $value);
|
||||
}
|
||||
}
|
||||
// Add body if present
|
||||
$body = $request->getBody();
|
||||
if ($body !== null) {
|
||||
$stream = $this->streamFactory->createStream($body);
|
||||
$psr7Request = $psr7Request->withBody($stream);
|
||||
}
|
||||
return $psr7Request;
|
||||
}
|
||||
/**
|
||||
* Converts a PSR-7 response to a custom Response.
|
||||
*
|
||||
* @since 0.1.0
|
||||
*
|
||||
* @param ResponseInterface $psr7Response The PSR-7 response.
|
||||
* @return Response The custom response.
|
||||
*/
|
||||
private function convertFromPsr7Response(ResponseInterface $psr7Response): Response
|
||||
{
|
||||
$body = (string) $psr7Response->getBody();
|
||||
// PSR-7 always returns headers as arrays, but HeadersCollection handles this
|
||||
return new Response(
|
||||
$psr7Response->getStatusCode(),
|
||||
$psr7Response->getHeaders(),
|
||||
// @phpstan-ignore-line
|
||||
$body === '' ? null : $body
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
<?php
|
||||
|
||||
declare (strict_types=1);
|
||||
namespace WordPress\AiClient\Providers\Http;
|
||||
|
||||
use WordPress\AiClientDependencies\Http\Discovery\Psr17FactoryDiscovery;
|
||||
use WordPress\AiClientDependencies\Http\Discovery\Psr18ClientDiscovery;
|
||||
use WordPress\AiClient\Providers\Http\Contracts\HttpTransporterInterface;
|
||||
/**
|
||||
* Factory for creating HTTP transporters.
|
||||
*
|
||||
* Uses HTTPlug's Discovery component to automatically find
|
||||
* available HTTP clients and factories.
|
||||
*
|
||||
* @since 0.1.0
|
||||
*/
|
||||
class HttpTransporterFactory
|
||||
{
|
||||
/**
|
||||
* Creates an HTTP transporter.
|
||||
*
|
||||
* Uses HTTPlug Discovery to automatically find PSR-18 client
|
||||
* and PSR-17 factories if not provided.
|
||||
*
|
||||
* @since 0.1.0
|
||||
*
|
||||
* @return HttpTransporterInterface The HTTP transporter.
|
||||
*/
|
||||
public static function createTransporter(): HttpTransporterInterface
|
||||
{
|
||||
return new \WordPress\AiClient\Providers\Http\HttpTransporter(Psr18ClientDiscovery::find(), Psr17FactoryDiscovery::findRequestFactory(), Psr17FactoryDiscovery::findStreamFactory());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
<?php
|
||||
|
||||
declare (strict_types=1);
|
||||
namespace WordPress\AiClient\Providers\Http\Traits;
|
||||
|
||||
use WordPress\AiClient\Common\Exception\RuntimeException;
|
||||
use WordPress\AiClient\Providers\Http\Contracts\HttpTransporterInterface;
|
||||
/**
|
||||
* Trait for a class that implements WithHttpTransporterInterface.
|
||||
*
|
||||
* @since 0.1.0
|
||||
*/
|
||||
trait WithHttpTransporterTrait
|
||||
{
|
||||
/**
|
||||
* @var HttpTransporterInterface|null The HTTP transporter instance.
|
||||
*/
|
||||
private ?HttpTransporterInterface $httpTransporter = null;
|
||||
/**
|
||||
* {@inheritDoc}
|
||||
*
|
||||
* @since 0.1.0
|
||||
*/
|
||||
public function setHttpTransporter(HttpTransporterInterface $httpTransporter): void
|
||||
{
|
||||
$this->httpTransporter = $httpTransporter;
|
||||
}
|
||||
/**
|
||||
* {@inheritDoc}
|
||||
*
|
||||
* @since 0.1.0
|
||||
*/
|
||||
public function getHttpTransporter(): HttpTransporterInterface
|
||||
{
|
||||
if ($this->httpTransporter === null) {
|
||||
throw new RuntimeException('HttpTransporterInterface instance not set. Make sure you use the AiClient class for all requests.');
|
||||
}
|
||||
return $this->httpTransporter;
|
||||
}
|
||||
}
|
||||
+40
@@ -0,0 +1,40 @@
|
||||
<?php
|
||||
|
||||
declare (strict_types=1);
|
||||
namespace WordPress\AiClient\Providers\Http\Traits;
|
||||
|
||||
use WordPress\AiClient\Common\Exception\RuntimeException;
|
||||
use WordPress\AiClient\Providers\Http\Contracts\RequestAuthenticationInterface;
|
||||
/**
|
||||
* Trait for a class that implements WithRequestAuthenticationInterface.
|
||||
*
|
||||
* @since 0.1.0
|
||||
*/
|
||||
trait WithRequestAuthenticationTrait
|
||||
{
|
||||
/**
|
||||
* @var RequestAuthenticationInterface|null The request authentication instance.
|
||||
*/
|
||||
private ?RequestAuthenticationInterface $requestAuthentication = null;
|
||||
/**
|
||||
* {@inheritDoc}
|
||||
*
|
||||
* @since 0.1.0
|
||||
*/
|
||||
public function setRequestAuthentication(RequestAuthenticationInterface $requestAuthentication): void
|
||||
{
|
||||
$this->requestAuthentication = $requestAuthentication;
|
||||
}
|
||||
/**
|
||||
* {@inheritDoc}
|
||||
*
|
||||
* @since 0.1.0
|
||||
*/
|
||||
public function getRequestAuthentication(): RequestAuthenticationInterface
|
||||
{
|
||||
if ($this->requestAuthentication === null) {
|
||||
throw new RuntimeException('RequestAuthenticationInterface instance not set. ' . 'Make sure you use the AiClient class for all requests.');
|
||||
}
|
||||
return $this->requestAuthentication;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,53 @@
|
||||
<?php
|
||||
|
||||
declare (strict_types=1);
|
||||
namespace WordPress\AiClient\Providers\Http\Util;
|
||||
|
||||
/**
|
||||
* Utility for extracting error messages from API response data.
|
||||
*
|
||||
* Centralizes the logic for parsing common API error response formats
|
||||
* to avoid code duplication across exception classes.
|
||||
*
|
||||
* @since 0.2.0
|
||||
* @since 0.4.0 Moved from Utilities namespace to Util namespace.
|
||||
*/
|
||||
class ErrorMessageExtractor
|
||||
{
|
||||
/**
|
||||
* Extracts error message from API response data.
|
||||
*
|
||||
* Handles common error response formats:
|
||||
* - { "error": { "message": "Error text" } }
|
||||
* - { "error": "Error text" }
|
||||
* - { "message": "Error text" }
|
||||
*
|
||||
* @since 0.2.0
|
||||
*
|
||||
* @param mixed $data The response data to extract error message from.
|
||||
* @return string|null The extracted error message, or null if none found.
|
||||
*/
|
||||
public static function extractFromResponseData($data): ?string
|
||||
{
|
||||
if (!is_array($data)) {
|
||||
return null;
|
||||
}
|
||||
// Handle [ { "error": { "message": "Error text" } } ]
|
||||
if (isset($data[0]) && is_array($data[0]) && isset($data[0]['error']) && is_array($data[0]['error']) && isset($data[0]['error']['message']) && is_string($data[0]['error']['message'])) {
|
||||
return $data[0]['error']['message'];
|
||||
}
|
||||
// Handle { "error": { "message": "Error text" } }
|
||||
if (isset($data['error']) && is_array($data['error']) && isset($data['error']['message']) && is_string($data['error']['message'])) {
|
||||
return $data['error']['message'];
|
||||
}
|
||||
// Handle { "error": "Error text" }
|
||||
if (isset($data['error']) && is_string($data['error'])) {
|
||||
return $data['error'];
|
||||
}
|
||||
// Handle { "message": "Error text" }
|
||||
if (isset($data['message']) && is_string($data['message'])) {
|
||||
return $data['message'];
|
||||
}
|
||||
return null;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,55 @@
|
||||
<?php
|
||||
|
||||
declare (strict_types=1);
|
||||
namespace WordPress\AiClient\Providers\Http\Util;
|
||||
|
||||
use WordPress\AiClient\Providers\Http\DTO\Response;
|
||||
use WordPress\AiClient\Providers\Http\Exception\ClientException;
|
||||
use WordPress\AiClient\Providers\Http\Exception\RedirectException;
|
||||
use WordPress\AiClient\Providers\Http\Exception\ServerException;
|
||||
/**
|
||||
* Class with static utility methods to process HTTP responses.
|
||||
*
|
||||
* @since 0.1.0
|
||||
*/
|
||||
class ResponseUtil
|
||||
{
|
||||
/**
|
||||
* Throws an appropriate exception if the given response is not successful.
|
||||
*
|
||||
* This method checks the HTTP status code of the response and throws
|
||||
* the appropriate exception type based on the status code range:
|
||||
* - 3xx: RedirectException (redirect responses)
|
||||
* - 4xx: ClientException (client errors)
|
||||
* - 5xx: ServerException (server errors)
|
||||
* - Other unsuccessful responses: RuntimeException (invalid status codes)
|
||||
*
|
||||
* @since 0.1.0
|
||||
*
|
||||
* @param Response $response The HTTP response to check.
|
||||
* @throws RedirectException If the response indicates a redirect (3xx).
|
||||
* @throws ClientException If the response indicates a client error (4xx).
|
||||
* @throws ServerException If the response indicates a server error (5xx).
|
||||
* @throws \RuntimeException If the response has an invalid status code.
|
||||
*/
|
||||
public static function throwIfNotSuccessful(Response $response): void
|
||||
{
|
||||
if ($response->isSuccessful()) {
|
||||
return;
|
||||
}
|
||||
$statusCode = $response->getStatusCode();
|
||||
// 3xx Redirect Responses
|
||||
if ($statusCode >= 300 && $statusCode < 400) {
|
||||
throw RedirectException::fromRedirectResponse($response);
|
||||
}
|
||||
// 4xx Client Errors
|
||||
if ($statusCode >= 400 && $statusCode < 500) {
|
||||
throw ClientException::fromClientErrorResponse($response);
|
||||
}
|
||||
// 5xx Server Errors
|
||||
if ($statusCode >= 500 && $statusCode < 600) {
|
||||
throw ServerException::fromServerErrorResponse($response);
|
||||
}
|
||||
throw new \RuntimeException(sprintf('Response returned invalid status code: %s', $response->getStatusCode()));
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user