wp-oop/http-client

A PSR-18 wrapper for the WordPress HTTP API

v0.1.0-alpha1 2023-08-18 14:16 UTC

This package is auto-updated.

Last update: 2024-11-30 02:33:32 UTC


README

Continuous Integration Packagist PHP Version Support Latest Stable Version Latest Unstable Version

A PSR-18 wrapper for the WordPress HTTP API.

Usage

use Psr\Http\Client\ClientExceptionInterface;
use Psr\Http\Message\RequestFactoryInterface;
use Psr\Http\Message\ResponseFactoryInterface;
use WpOop\HttpClient\Client;

/** @var RequestFactoryInterface $requestFactory */
/** @var ResponseFactoryInterface $responseFactory */

// Set up the client with WP request options
// https://developer.wordpress.org/reference/classes/wp_http/request/
$client = new Client(
    // Default args to WP_Http::request()
    [
        'redirection' => 2,
        'timeout' => 60,
    ],
    $responseFactory,
    // Path to proxy file dir to enable response streaming.
    // If null, will buffer in memory instead.
    get_temp_dir() 
);

// Create a PSR-7 request in any way you want, for example via a PSR-17 factory
$request = $requestFactory->createRequest('GET', 'http://somesite.com/api');

try {
    // Send a request as usual, consuming a familiar PSR-18 interface
    $response = $client->sendRequest($request);
} catch (ClientExceptionInterface $e) {
    // Handle PSR-18 exceptions
}

Since this is a PSR-18-compliant implementation, you can consume it in the way you would any other.

To set it up, pass a map of WP request options, and a PSR-17 response factory. This approach facilitates decoupling from any concrete PSR-7 implementation.

You can use any PSR-17 implementation or PSR-7 implementations. I suggest the slim and efficient nyholm/psr7, which conveniently implements both.

Limitations

Currently only throws ClientExceptionInterface, as it is unable to reliably determine whether a network or another specific kind of problem has occurred from the error value returned by wp_remote_request().