gitlab_time_tracker-8.x-1.x-dev/src/GitlabMutationsClient.php

src/GitlabMutationsClient.php
<?php

namespace Drupal\gitlab_time_tracker;

use Drupal\Core\Config\ConfigFactoryInterface;
use Drupal\Core\Site\Settings;
use Gitlab\Client;
use GuzzleHttp\Client as HttpClient;
use Symfony\Component\HttpFoundation\Session\Session;

/**
 * Class GitlabMutationsClient.
 */
class GitlabMutationsClient {

  /**
   * Drupal\Core\Config\ConfigManagerInterface definition.
   *
   * @var \Drupal\Core\Config\ConfigFactoryInterface
   */
  protected $configFactory;

  /**
   * \GuzzleHttp\Client instance.
   *
   * @var \GuzzleHttp\Client
   */
  protected $httpClient;

  /**
   * Constructs a new GitlabMutationsClient object.
   */
  public function __construct(ConfigFactoryInterface $config_factory, HttpClient $http_client, Session $session) {
    $this->configFactory = $config_factory;
    $this->httpClient = $http_client;
    $this->session = $session;
  }

  /**
   * Get client request.
   */
  protected function getClient() {
    $config = Settings::get('gitlab');

    if ($user_token = $this->session->get('gitlab_token')) {
      $token = $user_token;
    }
    else {
      $token = $config['api_token'];
    }

    return Client::create($config['url'])
      ->authenticate($config['api_token'], Client::AUTH_URL_TOKEN);
  }

  /**
   * Get custom request.
   */
  protected function getRequest($endpoint, $type, $payload) {
    $config = Settings::get('gitlab');

    if ($user_token = $this->session->get('gitlab_token')) {
      $token = $user_token->getToken();
      $headers = [
        'Authorization' => "Bearer {$token}",
      ];
    }
    else {
      $token = $config['api_token'];

      $headers = [
        'Private-Token' => "{$token}",
      ];
    }

    try {
      $response = $this->httpClient->request(
        $type,
        $config['url'] . $endpoint,
        [
          'headers' => $headers,
          'json' => $payload,
        ]
      );
      $headers = $response->getHeaders();

      if ($response->getStatusCode() == '200') {
        return json_decode($response->getBody()->getContents(), TRUE);
      }
    }
    catch (\Exception $e) {
      return [];
    }
  }

  /**
   * Update issue time record.
   */
  public function updateIssueTime($project_id, $issue_iid, $spent) {
    // Reset spent time.
    $output = $this->getRequest(
      "projects/{$project_id}/issues/{$issue_iid}/reset_spent_time",
      "POST",
      []
    );
    $this->getRequest(
      "projects/{$project_id}/issues/{$issue_iid}/add_spent_time?duration={$spent}",
      "POST",
      []
    );
  }

}

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

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