class-google.php
<?php
namespace HivePress\Components;
use HivePress\Helpers as hp;
use League\OAuth2\Client\Provider;
use League\OAuth2\Client\Grant;
defined( 'ABSPATH' ) || exit;
final class Google extends Component {
public function is_enabled() {
return get_option( 'hp_google_client_id' ) && get_option( 'hp_google_client_secret' );
}
public function get_client() {
return new Provider\Google(
[
'accessType' => 'offline',
'clientId' => get_option( 'hp_google_client_id' ),
'clientSecret' => get_option( 'hp_google_client_secret' ),
'redirectUri' => hivepress()->router->get_url( 'google_oauth_grant_access_action' ),
]
);
}
public function get_token( $namespace ) {
$prefix = hp\prefix( $namespace );
$access_token = get_option( $prefix . '_access_token', null );
if ( $access_token ) {
$expiration = absint( get_option( $prefix . '_token_expiration' ) );
if ( $expiration <= time() ) {
$refresh_token = get_option( $prefix . '_refresh_token' );
$client = $this->get_client();
try {
$token = $client->getAccessToken(
( new Grant\RefreshToken() ),
[
'refresh_token' => $refresh_token,
]
);
} catch ( \Exception $exception ) {
$this->delete_token( $namespace );
return;
}
$this->update_token( $namespace, $token );
$access_token = $token->getToken();
}
}
return $access_token;
}
public function update_token( $namespace, $token ) {
$prefix = hp\prefix( $namespace );
update_option( $prefix . '_access_token', $token->getToken() );
update_option( $prefix . '_token_expiration', $token->getExpires() );
if ( $token->getRefreshToken() ) {
update_option( $prefix . '_refresh_token', $token->getRefreshToken() );
}
}
public function delete_token( $namespace ) {
$prefix = hp\prefix( $namespace );
delete_option( $prefix . '_access_token' );
delete_option( $prefix . '_token_expiration' );
delete_option( $prefix . '_refresh_token' );
}
}