<?php
/**
 * Lightweight OAuth token provider for PHPMailer XOAUTH2.
 *
 * @package MailDoctor
 */

namespace MailDoctor;

if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

/**
 * Supplies pre-fetched OAuth tokens to PHPMailer.
 */
class OAuthTokenCredential {


	/**
	 * Authorized username/email address.
	 *
	 * @var string
	 */
	protected $username;

	/**
	 * Access token string.
	 *
	 * @var string
	 */
	protected $access_token;

	/**
	 * Constructor.
	 *
	 * @param string $username     Mailbox identifier.
	 * @param string $access_token Bearer token.
	 */
	public function __construct( string $username, string $access_token ) {
		$this->username     = $username;
		$this->access_token = $access_token;
	}

	/**
	 * Provide a base64-encoded SASL XOAUTH2 token string.
	 *
	 * @return string
	 */
	public function getOauth64(): string {
		$auth_string = sprintf(
			"user=%s\001auth=Bearer %s\001\001",
			$this->username,
			$this->access_token
		);

		return base64_encode( $auth_string );
	}
}
