| 1 |
<?php |
| 2 |
|
| 3 |
namespace Sendy\WooCommerce; |
| 4 |
|
| 5 |
use Sendy\Api\Connection; |
| 6 |
|
| 7 |
class ApiClientFactory |
| 8 |
{ |
| 9 |
private static ?Connection $connection = null; |
| 10 |
|
| 11 |
public static function buildBaseConnection(): Connection |
| 12 |
{ |
| 13 |
return (new Connection()) |
| 14 |
->setTransport(new Transport()) |
| 15 |
->setClientId(get_option('sendy_client_id')) |
| 16 |
->setClientSecret(get_option('sendy_client_secret')) |
| 17 |
->setUserAgentAppendix( |
| 18 |
sprintf('WooCommerce/%s Sendy/%s', WC_VERSION, Plugin::VERSION), |
| 19 |
) |
| 20 |
->setOauthClient(true) |
| 21 |
->setRedirectUrl(sendy_oauth_redirect_url()) |
| 22 |
->setTokenUpdateCallback(function (Connection $connection) { |
| 23 |
update_option('sendy_access_token', $connection->getAccessToken(), false); |
| 24 |
update_option('sendy_refresh_token', $connection->getRefreshToken(), false); |
| 25 |
update_option('sendy_token_expires', $connection->getTokenExpires(), false); |
| 26 |
}) |
| 27 |
; |
| 28 |
} |
| 29 |
|
| 30 |
public static function buildConnectionUsingCode(string $code): Connection |
| 31 |
{ |
| 32 |
if (! self::$connection instanceof Connection) { |
| 33 |
self::$connection = self::buildBaseConnection()->setAuthorizationCode($code); |
| 34 |
} |
| 35 |
|
| 36 |
return self::$connection; |
| 37 |
} |
| 38 |
|
| 39 |
public static function buildConnectionUsingTokens(): Connection |
| 40 |
{ |
| 41 |
if (get_option('sendy_access_token') == '' || get_option('sendy_refresh_token') == '' || get_option('sendy_token_expires') == '') { |
| 42 |
throw new \RuntimeException('Please authenticate first before using this method'); |
| 43 |
} |
| 44 |
|
| 45 |
if (! self::$connection instanceof Connection) { |
| 46 |
return self::$connection = self::buildBaseConnection() |
| 47 |
->setAccessToken(get_option('sendy_access_token')) |
| 48 |
->setRefreshToken(get_option('sendy_refresh_token')) |
| 49 |
->setTokenExpires(get_option('sendy_token_expires')) |
| 50 |
; |
| 51 |
} |
| 52 |
|
| 53 |
return self::$connection; |
| 54 |
} |
| 55 |
} |
| 56 |
|