drupalorg-1.0.x-dev/src/Utilities/GitLabTokenRenew.php

src/Utilities/GitLabTokenRenew.php
<?php

namespace Drupal\drupalorg\Utilities;

use Drupal\drupalorg\Traits\GitLabClientTrait;

/**
 * Utility functions to renew the GitLab token.
 */
class GitLabTokenRenew {

  use GitLabClientTrait;

  /**
   * Renew the token.
   *
   * @param int $days_before_expiry
   *   Days to consider before expiry (>= 1).
   *
   * @return bool
   *   Whether the token was renewed or not.
   */
  public function renewToken($days_before_expiry = 2) {
    // We want to renew at least the day before.
    if ($days_before_expiry < 1) {
      $days_before_expiry = 1;
    }

    $client = $this->getGitLabClient();
    $config = \Drupal::getContainer()->get('config.factory')->getEditable('drupalorg.gitlab_settings');
    if ($config->get('renew_token_on_cron')) {
      $current_token = $client->personal_access_tokens()->current();
      if (!empty($current_token['id'])) {
        $days_to_expiry = $this->calculateExpiryIntervalInDays($current_token);

        // Renew token only if it expires within the next couple of days,
        // or it is already expired.
        if ($days_to_expiry < $days_before_expiry) {
          $token = $client->personal_access_tokens()->rotate($current_token['id']);
          $new_token = $token['token'];
          if ($new_token) {
            $config->set('token', $new_token)->save();
            return TRUE;
          }
        }
      }
    }

    return FALSE;
  }

  /**
   * Returns how many days are left until the current token expires.
   *
   * @return int|null
   *   Days until the current token expires. Null if no token is found.
   */
  public function daysToExpiry() {
    $current_token = $this->getGitLabClient()->personal_access_tokens()->current();
    if (!empty($current_token['id'])) {
      return $this->calculateExpiryIntervalInDays($current_token);
    }

    return NULL;
  }

  /**
   * Calculates the days remaining for a token to expire.
   *
   * @param array $token
   *   Token array as returned by the GitLab library.
   *
   * @return int
   *   Number of days until the expiry. Negative values if expired.
   */
  private function calculateExpiryIntervalInDays($token) {
    $utc = new \DateTimeZone('UTC');
    $expires_at = new \DateTime($token['expires_at'], $utc);
    $now = new \DateTimeImmutable('now', $utc);
    $interval = $now->diff($expires_at)->days;
    if ($now > $expires_at) {
      $interval = -1 * $interval;
    }

    return $interval;
  }

}

Главная | Обратная связь

drupal hosting | друпал хостинг | it patrol .inc