diff --git a/src/ConvertKit_API.php b/src/ConvertKit_API.php index 84d1cc1..8eb4e92 100644 --- a/src/ConvertKit_API.php +++ b/src/ConvertKit_API.php @@ -10,6 +10,7 @@ use Monolog\Logger; use Monolog\Handler\StreamHandler; use GuzzleHttp\Client; +use GuzzleHttp\ClientInterface; use GuzzleHttp\Psr7\Request; /** @@ -67,9 +68,9 @@ class ConvertKit_API protected $debug_logger; /** - * Guzzle Http Client + * Guzzle Http ClientInterface * - * @var \GuzzleHttp\Client + * @var \GuzzleHttp\ClientInterface */ protected $client; @@ -87,7 +88,7 @@ public function __construct(string $api_key, string $api_secret, bool $debug = f $this->api_secret = $api_secret; $this->debug = $debug; - // Specify a User-Agent for API requests. + // Set the Guzzle client. $this->client = new Client( [ 'headers' => [ @@ -105,6 +106,20 @@ public function __construct(string $api_key, string $api_secret, bool $debug = f } } + /** + * Set the Guzzle client implementation to use for API requests. + * + * @param ClientInterface $client Guzzle client implementation. + * + * @since 1.3.0 + * + * @return void + */ + public function set_http_client(ClientInterface $client) + { + $this->client = $client; + } + /** * Add an entry to monologger. * diff --git a/tests/ConvertKitAPITest.php b/tests/ConvertKitAPITest.php index 56483c2..d7ccfa5 100644 --- a/tests/ConvertKitAPITest.php +++ b/tests/ConvertKitAPITest.php @@ -1,6 +1,12 @@ api = new \ConvertKit_API\ConvertKit_API($_ENV['CONVERTKIT_API_KEY'], $_ENV['CONVERTKIT_API_SECRET']); } + /** + * Test that a ClientInterface can be injected. + * + * @since 1.3.0 + * + * @return void + */ + public function testClientInterfaceInjection() + { + // Setup API with a mock Guzzle client. + $mock = new MockHandler([ + new Response(200, [], json_encode( + [ + 'name' => 'Test Account for Guzzle Mock', + 'plan_type' => 'free', + 'primary_email_address' => 'mock@guzzle.mock', + ] + )), + ]); + + // Define client with mock handler. + $handlerStack = HandlerStack::create($mock); + $client = new Client(['handler' => $handlerStack]); + + // Assign the client to the API class. + $this->api->set_http_client($client); + + // Perform an API request. + $result = $this->api->get_account(); + + // Confirm mocked data was returned. + $this->assertSame('Test Account for Guzzle Mock', $result->name); + $this->assertSame('free', $result->plan_type); + $this->assertSame('mock@guzzle.mock', $result->primary_email_address); + } + /** * Test that debug logging works when enabled and an API call is made. *