diff --git a/CHANGELOG.md b/CHANGELOG.md index 3e4f3e5..a0c9ec0 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,6 +5,11 @@ The format is based on [Keep a Changelog](http://keepachangelog.com/) and this project adheres to [Semantic Versioning](http://semver.org/). ## [Unreleased] +### Added +- Support for API token authentication. Username and password can still be used + as a fallback. +### Changed +- Deprecate `getConfig()` method. Packages can maintain their config internally. ## [5.1.1] - 2021-08-10 ### Fixed diff --git a/README.md b/README.md index 1f40d73..f8d47c4 100644 --- a/README.md +++ b/README.md @@ -36,8 +36,7 @@ $ composer require maxemail/api-php ```php // Instantiate Client: $config = [ - 'username' => 'api@user.com', - 'password' => 'apipass' + 'token' => 'apitoken', ]; $api = new \Maxemail\Api\Client($config); diff --git a/phpunit.xml.dist b/phpunit.xml.dist index e6230c1..8a738f1 100644 --- a/phpunit.xml.dist +++ b/phpunit.xml.dist @@ -12,8 +12,7 @@ - - + diff --git a/src/Client.php b/src/Client.php index b041f32..5ae1fa6 100644 --- a/src/Client.php +++ b/src/Client.php @@ -5,6 +5,7 @@ namespace Maxemail\Api; use GuzzleHttp\Client as GuzzleClient; +use GuzzleHttp\ClientInterface as GuzzleClientInterface; use GuzzleHttp\HandlerStack; use Psr\Log\LoggerInterface; @@ -65,6 +66,11 @@ class Client implements \Psr\Log\LoggerAwareInterface */ private $uri = 'https://mxm.xtremepush.com/'; + /** + * @var string + */ + private $token; + /** * @var string */ @@ -91,7 +97,7 @@ class Client implements \Psr\Log\LoggerAwareInterface private $logger; /** - * @var GuzzleClient + * @var GuzzleClientInterface */ private $httpClient; @@ -100,6 +106,11 @@ class Client implements \Psr\Log\LoggerAwareInterface */ private $debugLoggingEnabled = false; + /** + * @var \Closure(array):GuzzleClientInterface + */ + private $httpClientFactory; + /** * @param array $config { * @var string $username Required @@ -112,20 +123,25 @@ class Client implements \Psr\Log\LoggerAwareInterface */ public function __construct(array $config) { - // Support deprecated key names from v3 - if (!isset($config['username']) && isset($config['user'])) { - $config['username'] = $config['user']; - } - if (!isset($config['password']) && isset($config['pass'])) { - $config['password'] = $config['pass']; - } + // Must have API token + if (!isset($config['token'])) { + // Support deprecated key names from v3 + if (!isset($config['username']) && isset($config['user'])) { + $config['username'] = $config['user']; + } + if (!isset($config['password']) && isset($config['pass'])) { + $config['password'] = $config['pass']; + } - // Must have user/pass - if (!isset($config['username']) || !isset($config['password'])) { - throw new Exception\InvalidArgumentException('API config requires username & password'); + // Must have user/pass + if (!isset($config['username']) || !isset($config['password'])) { + throw new Exception\InvalidArgumentException('API config requires token OR username & password'); + } + $this->username = $config['username']; + $this->password = $config['password']; + } else { + $this->token = $config['token']; } - $this->username = $config['username']; - $this->password = $config['password']; if (isset($config['uri'])) { $parsed = parse_url($config['uri']); @@ -157,7 +173,7 @@ private function getInstance(string $serviceName): Service return $this->services[$serviceName]; } - private function getClient(): GuzzleClient + private function getClient(): GuzzleClientInterface { if ($this->httpClient === null) { $stack = HandlerStack::create(); @@ -166,19 +182,31 @@ private function getClient(): GuzzleClient if ($this->debugLoggingEnabled) { Middleware::addLogging($stack, $this->getLogger()); } - $this->httpClient = new GuzzleClient([ + + $clientConfig = [ 'base_uri' => $this->uri . 'api/json/', - 'auth' => [ - $this->username, - $this->password, - ], 'headers' => [ 'User-Agent' => 'MxmApiClient/' . self::VERSION . ' PHP/' . PHP_VERSION, 'Content-Type' => 'application/x-www-form-urlencoded', 'Accept' => 'application/json', ], 'handler' => $stack, - ]); + ]; + + if (isset($this->token)) { + $clientConfig['headers']['Authorization'] = 'Bearer ' . $this->token; + } else { + $clientConfig['auth'] = [ + $this->username, + $this->password, + ]; + } + + if (!isset($this->httpClientFactory)) { + $this->httpClient = new GuzzleClient($clientConfig); + } else { + $this->httpClient = ($this->httpClientFactory)($clientConfig); + } } return $this->httpClient; @@ -187,6 +215,7 @@ private function getClient(): GuzzleClient /** * Get API connection config * + * @deprecated v5.2 No replacement; packages can maintain their own config; to be removed in v7. * @return array { * @var string $uri * @var string $username @@ -224,4 +253,12 @@ public function getLogger(): LoggerInterface return $this->logger; } + + /** + * @internal This method is not part of the BC promise. Used for DI for unit tests only. + */ + public function setHttpClientFactory(\Closure $httpClientFactory): void + { + $this->httpClientFactory = $httpClientFactory; + } } diff --git a/src/Helper.php b/src/Helper.php index 5c940ba..262f534 100644 --- a/src/Helper.php +++ b/src/Helper.php @@ -4,7 +4,7 @@ namespace Maxemail\Api; -use GuzzleHttp\Client as GuzzleClient; +use GuzzleHttp\ClientInterface as GuzzleClient; use Psr\Log\LogLevel; /** diff --git a/src/Service.php b/src/Service.php index e56beeb..13b0f30 100644 --- a/src/Service.php +++ b/src/Service.php @@ -4,7 +4,7 @@ namespace Maxemail\Api; -use GuzzleHttp\Client as GuzzleClient; +use GuzzleHttp\ClientInterface as GuzzleClient; /** * Maxemail API Client diff --git a/tests/ClientTest.php b/tests/ClientTest.php index 47d0256..370a511 100644 --- a/tests/ClientTest.php +++ b/tests/ClientTest.php @@ -4,6 +4,7 @@ namespace Maxemail\Api; +use GuzzleHttp\ClientInterface as GuzzleClient; use PHPUnit\Framework\MockObject\MockObject; use PHPUnit\Framework\TestCase; @@ -18,15 +19,32 @@ class ClientTest extends TestCase { private $testConfig = [ 'uri' => 'https://maxemail.example.com/', - 'username' => 'api@user.com', - 'password' => 'apipass', + 'token' => 'apitoken', ]; public function testConfigValid() { $api = new Client($this->testConfig); - $this->assertSame($this->testConfig, $api->getConfig()); + $factory = function (array $actual): GuzzleClient { + $expectedUri = $this->testConfig['uri'] . 'api/json/'; + static::assertSame($expectedUri, $actual['base_uri']); + + $expectedHeaders = [ + 'User-Agent' => 'MxmApiClient/' . Client::VERSION . ' PHP/' . PHP_VERSION, + 'Content-Type' => 'application/x-www-form-urlencoded', + 'Accept' => 'application/json', + 'Authorization' => 'Bearer ' . $this->testConfig['token'], + ]; + static::assertSame($expectedHeaders, $actual['headers']); + + return $this->createMock(GuzzleClient::class); + }; + + $api->setHttpClientFactory($factory); + + // Get a service, to trigger the HTTP Client factory + $api->folder; } public function testConfigSupportDeprecatedUserPass() @@ -38,33 +56,63 @@ public function testConfigSupportDeprecatedUserPass() $api = new Client($config); - $this->assertSame($config['user'], $api->getConfig()['username']); - $this->assertSame($config['pass'], $api->getConfig()['password']); + $factory = function (array $actual) use ($config): GuzzleClient { + $expectedAuth = [ + $config['user'], + $config['pass'], + ]; + static::assertSame($expectedAuth, $actual['auth']); + + return $this->createMock(GuzzleClient::class); + }; + + $api->setHttpClientFactory($factory); + + // Get a service, to trigger the HTTP Client factory + $api->folder; } public function testConfigDefaultHost() { $config = [ - 'username' => 'api@user.com', - 'password' => 'apipass', + 'token' => 'apitoken', ]; $api = new Client($config); - $this->assertSame('https://mxm.xtremepush.com/', $api->getConfig()['uri']); + $factory = function (array $actual) use ($config): GuzzleClient { + $expectedUri = 'https://mxm.xtremepush.com/api/json/'; + static::assertSame($expectedUri, $actual['base_uri']); + + return $this->createMock(GuzzleClient::class); + }; + + $api->setHttpClientFactory($factory); + + // Get a service, to trigger the HTTP Client factory + $api->folder; } public function testConfigStripsUriPath() { $config = [ - 'uri' => 'http://maxemail.example.com/some/extra/path', - 'username' => 'api@user.com', - 'password' => 'apipass', + 'uri' => 'https://maxemail.example.com/some/extra/path', + 'token' => 'apitoken', ]; $api = new Client($config); - $this->assertSame('http://maxemail.example.com/', $api->getConfig()['uri']); + $factory = function (array $actual) use ($config): GuzzleClient { + $expectedUri = 'https://maxemail.example.com/api/json/'; + static::assertSame($expectedUri, $actual['base_uri']); + + return $this->createMock(GuzzleClient::class); + }; + + $api->setHttpClientFactory($factory); + + // Get a service, to trigger the HTTP Client factory + $api->folder; } public function testConfigInvalidUri() @@ -74,8 +122,7 @@ public function testConfigInvalidUri() $config = [ 'uri' => '//', - 'username' => 'api@user.com', - 'password' => 'apipass', + 'token' => 'apitoken', ]; new Client($config); @@ -88,17 +135,49 @@ public function testConfigMissingUriProtocol() $config = [ 'uri' => 'maxemail.example.com', + 'token' => 'apitoken', + ]; + + new Client($config); + } + + public function testConfigLegacyAuthentication(): void + { + $config = [ 'username' => 'api@user.com', 'password' => 'apipass', ]; - new Client($config); + $api = new Client($config); + + $factory = function (array $actual) use ($config): GuzzleClient { + $expectedAuth = [ + $config['username'], + $config['password'], + ]; + static::assertSame($expectedAuth, $actual['auth']); + + return $this->createMock(GuzzleClient::class); + }; + + $api->setHttpClientFactory($factory); + + // Get a service, to trigger the HTTP Client factory + $api->folder; + } + + public function testConfigMissingToken(): void + { + $this->expectException(Exception\InvalidArgumentException::class); + $this->expectExceptionMessage('API config requires token OR username & password'); + + new Client([]); } public function testConfigMissingUsername(): void { $this->expectException(Exception\InvalidArgumentException::class); - $this->expectExceptionMessage('API config requires username & password'); + $this->expectExceptionMessage('API config requires token OR username & password'); $config = [ 'password' => 'apipass', @@ -110,7 +189,7 @@ public function testConfigMissingUsername(): void public function testConfigMissingPassword(): void { $this->expectException(Exception\InvalidArgumentException::class); - $this->expectExceptionMessage('API config requires username & password'); + $this->expectExceptionMessage('API config requires token OR username & password'); $config = [ 'username' => 'api@user.com', @@ -119,6 +198,32 @@ public function testConfigMissingPassword(): void new Client($config); } + public function testGetConfigWithToken(): void + { + $api = new Client($this->testConfig); + + $expected = [ + 'uri' => $this->testConfig['uri'], + 'username' => null, + 'password' => null, + ]; + + static::assertSame($expected, $api->getConfig()); + } + + public function testGetConfigWithLegacyAuthentication(): void + { + $config = [ + 'uri' => 'https://maxemail.example.com/', + 'username' => 'api@user.com', + 'password' => 'apipass', + ]; + + $api = new Client($config); + + static::assertSame($config, $api->getConfig()); + } + public function testSetGetLogger() { /** @var \Psr\Log\LoggerInterface|MockObject $logger */ diff --git a/tests/FunctionalTest.php b/tests/FunctionalTest.php index 5df4ca7..21567bd 100644 --- a/tests/FunctionalTest.php +++ b/tests/FunctionalTest.php @@ -30,8 +30,7 @@ protected function setUp(): void $config = [ 'uri' => getenv('FUNC_API_URI'), - 'username' => getenv('FUNC_API_USERNAME'), - 'password' => getenv('FUNC_API_PASSWORD'), + 'token' => getenv('FUNC_API_TOKEN'), ]; $this->client = new Client($config); }