|
| 1 | +<?php |
| 2 | + |
| 3 | +namespace FullscreenInteractive\SilverStripeXero; |
| 4 | + |
| 5 | +use SilverStripe\Control\Controller; |
| 6 | +use SilverStripe\Control\Director; |
| 7 | +use SilverStripe\Core\Environment; |
| 8 | +use SilverStripe\Core\Injector\Injectable; |
| 9 | +use SilverStripe\SiteConfig\SiteConfig; |
| 10 | + |
| 11 | +class XeroFactory |
| 12 | +{ |
| 13 | + use Injectable; |
| 14 | + |
| 15 | + /** |
| 16 | + * @var \XeroPHP\Application |
| 17 | + */ |
| 18 | + protected $application; |
| 19 | + |
| 20 | + /** |
| 21 | + * Setup |
| 22 | + */ |
| 23 | + public function setupApplication() |
| 24 | + { |
| 25 | + $provider = $this->getProvider(); |
| 26 | + $config = SiteConfig::current_site_config(); |
| 27 | + |
| 28 | + $newAccessToken = $provider->getAccessToken('refresh_token', [ |
| 29 | + 'refresh_token' => $config->XeroRefreshToken |
| 30 | + ]); |
| 31 | + |
| 32 | + $config->XeroAccessToken = $newAccessToken->getToken(); |
| 33 | + |
| 34 | + $refresh = $newAccessToken->getRefreshToken(); |
| 35 | + |
| 36 | + if ($refresh) { |
| 37 | + $config->XeroRefreshToken = $refresh; |
| 38 | + } |
| 39 | + |
| 40 | + $config->write(); |
| 41 | + } |
| 42 | + |
| 43 | + /** |
| 44 | + * @return \XeroPHP\Application |
| 45 | + */ |
| 46 | + public function getApplication() |
| 47 | + { |
| 48 | + if (!$this->application) { |
| 49 | + $this->setupApplication(); |
| 50 | + } |
| 51 | + |
| 52 | + return $this->application; |
| 53 | + } |
| 54 | + |
| 55 | + /** |
| 56 | + * @return \Calcinai\OAuth2\Client\Provider\Xero |
| 57 | + */ |
| 58 | + public function getProvider() |
| 59 | + { |
| 60 | + return new \Calcinai\OAuth2\Client\Provider\Xero([ |
| 61 | + 'clientId' => Environment::getEnv('XERO_CLIENT_ID'), |
| 62 | + 'clientSecret' => Environment::getEnv('XERO_CLIENT_SECRET'), |
| 63 | + 'redirectUri' => $this->getRedirectUri() |
| 64 | + ]); |
| 65 | + } |
| 66 | + |
| 67 | + /** |
| 68 | + * @return string |
| 69 | + */ |
| 70 | + public function getRedirectUri() |
| 71 | + { |
| 72 | + return Controller::join_links( |
| 73 | + Director::absoluteBaseURL(), |
| 74 | + 'connectXero' |
| 75 | + ); |
| 76 | + } |
| 77 | +} |
0 commit comments