From 8c19021aabd83ed421a206905e1261224d38deb6 Mon Sep 17 00:00:00 2001 From: Jesse Tolj Date: Wed, 5 Jul 2023 16:24:04 +0100 Subject: [PATCH] Allow injection of Guzzle/ClientInterface for mocking (or other) purposes --- src/ConvertKit_API.php | 18 +++++++++++++++--- tests/ConvertKitAPITest.php | 37 +++++++++++++++++++++++++++++++++++++ 2 files changed, 52 insertions(+), 3 deletions(-) diff --git a/src/ConvertKit_API.php b/src/ConvertKit_API.php index 84d1cc1..c94db16 100644 --- a/src/ConvertKit_API.php +++ b/src/ConvertKit_API.php @@ -8,10 +8,10 @@ namespace ConvertKit_API; use Monolog\Logger; -use Monolog\Handler\StreamHandler; use GuzzleHttp\Client; use GuzzleHttp\Psr7\Request; - +use GuzzleHttp\ClientInterface; +use Monolog\Handler\StreamHandler; /** * ConvertKit API Class */ @@ -69,7 +69,7 @@ class ConvertKit_API /** * Guzzle Http Client * - * @var \GuzzleHttp\Client + * @var \GuzzleHttp\ClientInterface */ protected $client; @@ -105,6 +105,18 @@ public function __construct(string $api_key, string $api_secret, bool $debug = f } } + /** + * Set the Guzzle client implementation to use. + * + * @param ClientInterface $client Guzzle client implementation. + * + * @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..29e4966 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. + * + * + * @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', + ] + )), + ]); + + $handlerStack = HandlerStack::create($mock); + $client = new Client(['handler' => $handlerStack]); + + $this->api->set_http_client($client); + + $result = $this->api->get_account(); + + $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. *