commercetools-8.x-1.2-alpha1/modules/commercetools_decoupled/src/CtAuth.php
modules/commercetools_decoupled/src/CtAuth.php
<?php
namespace Drupal\commercetools_decoupled;
use Commercetools\Client\OAuth2Handler;
use Drupal\commercetools\CommercetoolsApiServiceInterface;
use Drupal\Component\Datetime\TimeInterface;
/**
* Service for obtaining Commercetools tokens.
*/
class CtAuth {
/**
* List of limited scopes for anonymous connections directly on the frontend.
*/
const SCOPES = [
'view_published_products',
'view_categories',
];
/**
* Auth Handler.
*
* @var \Commercetools\Client\OAuth2Handler
*/
protected OAuth2Handler $authHandler;
/**
* CtAuth constructor.
*
* @param \Drupal\commercetools\CommercetoolsApiServiceInterface $ctApi
* The Commercetools API service.
* @param \Drupal\Component\Datetime\TimeInterface $time
* System time service.
*/
public function __construct(
protected CommercetoolsApiServiceInterface $ctApi,
protected TimeInterface $time,
) {}
/**
* Builds the OAuth2 Authorization header for FE requests.
*
* @return string
* The Authorization header value.
*/
public function getAuthorizationHeader(): string {
$this->authHandler = $this->ctApi->getAuthHandler(scope: static::SCOPES);
return $this->authHandler->getAuthorizationHeader();
}
/**
* Calculates the absolute cache expiry for the current access token.
*
* @return int
* UNIX timestamp when the token/header expires.
*/
public function getCacheExpire(): int {
return $this->time->getRequestTime() + $this->authHandler->refreshToken()->getExpiresIn();
}
}
