badgr_badge-8.x-1.x-dev/src/BadgrService.php

src/BadgrService.php
<?php

namespace Drupal\badgr_badge;

use Drupal\Core\Session\AccountInterface;
use GuzzleHttp\Exception\RequestException;
use Drupal\Component\Serialization\Json;
use GuzzleHttp\ClientInterface;
use Drupal\node\Entity\Node;

/**
 * Badgr token api uri
 */
const BADGR_TOKEN_API = 'https://api.badgr.io/o/token';

/**
 * Badgr user authenticate api uri
 */
const BADGR_USER_AUTHENTICATE_API = 'https://api.badgr.io/v2/users/self';

/**
 * Badgr issuers api uri
 */
const BADGR_ISSUERS = 'https://api.badgr.io/v2/issuers';

/**
 * Badgr badgeclass api uri
 */
const BADGR_BADGECLASS = 'https://api.badgr.io/v2/badgeclasses';

/**
 * Class BadgrService.
 */
class BadgrService implements BadgrServiceInterface {

  /**
   * The current user.
   *
   * @var \Drupal\Core\Session\AccountProxyInterface
   */
  protected $currentUser;

  /**
   * An http client.
   *
   * @var \GuzzleHttp\ClientInterface
   */
  protected $httpClient;

  /**
   * Constructs a new BadgrService object.
   *
   * @param \Drupal\Core\Session\AccountInterface $currentUser
   *    An current user.
   * @param \GuzzleHttp\ClientInterface $http_client
   *    An HTTP client.
   */
  public function __construct(AccountInterface $currentUser, ClientInterface $http_client) {
    $this->currentUser = $currentUser;
    $this->httpClient = $http_client;
  }

  /**
   * Initiating badgr authentication by User details
   *
   * @param array $_post_details
   *
   * @return mixed
   * @throws \GuzzleHttp\Exception\GuzzleException
   */
  public function badgr_initiate(array $_post_details) {

    try {
      $request = $this->httpClient->request('POST', BADGR_TOKEN_API, [
        'verify' => true,
        'form_params' => $_post_details
      ]);
      $access_token_data = Json::decode($request->getBody()->getContents());
    }
    catch (RequestException $e) {
      //An error happened.
      if ($e->hasResponse()) {
        $response = $e->getResponse();
        return Json::decode((string) $response->getBody());
      }
    }

    return $access_token_data;
  }

  /**
   * Refreshing the token if the access token gets expired.
   *
   * @param string $refresh_token
   *
   * @return mixed
   * @throws \GuzzleHttp\Exception\GuzzleException
   */
  public function badgr_refresh_token(string $refresh_token) {
    $_post_details = [
      'grant_type' => 'refresh_token',
      'refresh_token' => $refresh_token
    ];

    try {
      $request = $this->httpClient->request('POST', BADGR_TOKEN_API, [
        'verify' => true,
        'form_params' => $_post_details
      ]);
      $access_token_data = Json::decode($request->getBody()->getContents());
    }
    catch (RequestException $e) {
      //An error happened.
      if ($e->hasResponse()) {
        watchdog_exception('badgr_badge', $e);
      }
    }

    return $access_token_data;
  }

  /**
   * Sets Badgr Header authorization
   *
   * @param string $access_token
   *
   * @return array
   */
  public function badgr_set_header(string $access_token) {
    return [
      'accept' => 'application/json',
      'Content-Type' => 'application/json',
      'Authorization' => 'Bearer ' . $access_token,
    ];

  }

  /**
   * To check whether the user is already authenticated.
   *
   * @param string $access_token
   *
   * @return boolean
   * @throws \GuzzleHttp\Exception\GuzzleException
   */
  public function badgr_user_authenticate(string $access_token) {
    $_headers = $this->badgr_set_header($access_token);

    try {
      $request = $this->httpClient->request('GET', BADGR_USER_AUTHENTICATE_API, [
        'headers' => $_headers
      ]);
      $access_token_data = Json::decode($request->getBody()->getContents());
    }
    catch (RequestException $e) {
      //An error happened.
      if ($e->hasResponse()) {
        return FALSE;
      }
    }

    return $access_token_data['status']['success'];
  }

  /**
   * To reinitiate the token based on the badgr account
   *
   * @param string $access_token
   * @param string $badgr_account_id
   */
  public function reauthenticate_token_badgr_account(string &$access_token, string $badgr_account_id) {
    if ($badgr_account_id) {
      $badge_account = Node::load($badgr_account_id);

      $badgr_refresh_token = $badge_account->get('field_badgr_refresh_token')->getValue();
      $badgr_refresh_data = $this->badgr_refresh_token($badgr_refresh_token[0]['value']);
      if (isset($badgr_refresh_data['access_token']) && isset($badgr_refresh_data['refresh_token'])) {
        $badge_account->set('field_badgr_access_token', $badgr_refresh_data['access_token']);
        $badge_account->set('field_badgr_refresh_token', $badgr_refresh_data['refresh_token']);
        $badge_account->save();
        $access_token = $badgr_refresh_data['access_token'];
      }
    }
  }


  /**
   * To create an issuer on the badgr account
   *
   * @param string $access_token
   * @param string $_post_details
   * @param string $badgr_account_id
   *
   * @return mixed
   * @throws \GuzzleHttp\Exception\GuzzleException
   */
  public function badgr_create_issuer(string $access_token, string $_post_details, string $badgr_account_id) {
    if (!$this->badgr_user_authenticate($access_token)) {
      $this->reauthenticate_token_badgr_account($access_token, $badgr_account_id);
    }

    $_headers = $this->badgr_set_header($access_token);

    try {
      $request = $this->httpClient->request('POST', BADGR_ISSUERS, [
        'verify' => true,
        'body' => $_post_details,
        'headers' => $_headers
      ]);

      $issuer_data = Json::decode($request->getBody()->getContents());
    }
    catch (RequestException $e) {
      //An error happened.
      if ($e->hasResponse()) {
        watchdog_exception('badgr_badge', $e);
      }
    }

    return $issuer_data;
  }

  /**
   * To read/update/delete an issuer on the badgr account
   *
   * @param string $access_token
   * @param string $entity_id
   * @param string|null $method
   * @param array|null $_post_details
   * @param int $badgr_account_id
   *
   * @return mixed
   * @throws \GuzzleHttp\Exception\GuzzleException
   */
  public function badgr_update_rud_issuer(string $access_token, string $entity_id, string $method = NULL, array $_post_details = NULL, int $badgr_account_id) {
    if (!$this->badgr_user_authenticate($access_token)) {
      $this->reauthenticate_token_badgr_account($access_token, $badgr_account_id);
    }

    $_headers = $this->badgr_set_header($access_token);

    try {
      $api_url = BADGR_ISSUERS . '/' . $entity_id;

      if ($method == 'PUT' && !empty($_post_details)) {
        $request = $this->httpClient->request($method, $api_url, [
          'verify' => true,
          'form_params' => $_post_details,
          'headers' => $_headers
        ]);
      }
      elseif ($method == 'DELETE') {
        $request = $this->httpClient->request($method, $api_url, [
          'verify' => true,
          'headers' => $_headers
        ]);
      }
      else {
        $request = $this->httpClient->request('GET', $api_url, [
          'verify' => true,
          'headers' => $_headers
        ]);
      }

      $issuer_data = Json::decode($request->getBody()->getContents());
    }
    catch (RequestException $e) {
      //An error happened.
      if ($e->hasResponse()) {
        watchdog_exception('badgr_badge', $e);
      }
    }

    return $issuer_data;
  }

  /**
   * To get list of issuer on the badgr account
   *
   * @param string $access_token
   * @param int $badgr_account_id
   *
   * @return mixed
   * @throws \GuzzleHttp\Exception\GuzzleException
   */
  public function badgr_list_all_issuer(string &$access_token, int $badgr_account_id) {
    if (!$this->badgr_user_authenticate($access_token)) {
      $this->reauthenticate_token_badgr_account($access_token, $badgr_account_id);
    }

    $_headers = $this->badgr_set_header($access_token);

    try {
      $request = $this->httpClient->request('GET', BADGR_ISSUERS, [
        'verify' => true,
        'headers' => $_headers
      ]);

      $issuer_data = Json::decode($request->getBody()->getContents());
    }
    catch (RequestException $e) {
      //An error happened.
      if ($e->hasResponse()) {
        $response = $e->getResponse();
        return Json::decode((string) $response->getBody());
      }
    }

    return $issuer_data;
  }

  /**
   * To get list of existing issuer on the badgr account
   *
   * @param string $access_token
   * @param int $badgr_account_id
   *
   * @return mixed
   * @throws \GuzzleHttp\Exception\GuzzleException
   */
  public function badgr_list_all_existing_issuer(string &$access_token, int $badgr_account_id) {
    $issuer_data = [];
    // Fetch all issuers from badgr
    $_all_issuers = $this->badgr_list_all_issuer($access_token, $badgr_account_id);

    if ($_all_issuers['status']['success']) {
      if (count($_all_issuers['result']) > 0) {
        foreach ($_all_issuers['result'] as $key_issuer => $value_issuer) {
          $issuer_data[$value_issuer['entityId']] = t($value_issuer['name']);
        }
      }
    }
    return $issuer_data;
  }

  /**
   * To create an based to the issuer on the badgr account
   *
   * @param string $access_token
   * @param string $_post_details
   * @param string $entity_id
   * @param int $badgr_account_id
   *
   * @return mixed
   * @throws \GuzzleHttp\Exception\GuzzleException
   */
  public function badgr_create_issuer_badges(string &$access_token, string $_post_details, string $entity_id, int $badgr_account_id) {
    if (!$this->badgr_user_authenticate($access_token)) {
      $this->reauthenticate_token_badgr_account($access_token, $badgr_account_id);
    }

    $_headers = $this->badgr_set_header($access_token);

    try {
      $api_url = BADGR_ISSUERS . '/' . $entity_id . '/badgeclasses';

      $request = $this->httpClient->request('POST', $api_url, [
        'verify' => true,
        'body' => $_post_details,
        'headers' => $_headers
      ]);

      $badges_data = Json::decode($request->getBody()->getContents());
    }
    catch (RequestException $e) {
      //An error happened.
      if ($e->hasResponse()) {
        watchdog_exception('badgr_badge', $e);
      }
    }

    return $badges_data;
  }

  /**
   * To get list of badges on the badgr account
   *
   * @param string $access_token
   * @param int $badgr_account_id
   *
   * @return mixed
   * @throws \GuzzleHttp\Exception\GuzzleException
   */
  public function badgr_list_all_badges(string &$access_token, int $badgr_account_id) {
    if (!$this->badgr_user_authenticate($access_token)) {
      $this->reauthenticate_token_badgr_account($access_token, $badgr_account_id);
    }

    $_headers = $this->badgr_set_header($access_token);

    try {
      $request = $this->httpClient->request('GET', BADGR_BADGECLASS, [
        'verify' => true,
        'headers' => $_headers
      ]);

      $issuer_data = Json::decode($request->getBody()->getContents());
    }
    catch (RequestException $e) {
      //An error happened.
      if ($e->hasResponse()) {
        watchdog_exception('badgr_badge', $e);
      }
    }

    return $issuer_data;
  }

  /**
   * To get list of badges on the badgr account
   *
   * @param string $access_token
   * @param int $badgr_account_id
   *
   * @return mixed
   * @throws \GuzzleHttp\Exception\GuzzleException
   */
  public function badgr_list_all_existing_badges(string &$access_token, int $badgr_account_id) {
    $badges_options = [];
    $_all_badges = $this->badgr_list_all_badges($access_token, $badgr_account_id);
    if ($_all_badges['status']['success']) {
      if (count($_all_badges['result']) > 0) {
        foreach ($_all_badges['result'] as $key_badges => $value_badges) {
          $badges_options[$value_badges['issuer']][$value_badges['entityId']] = t($value_badges['name']);
        }
      }
    }
    return $badges_options;
  }

  /**
   * To read/update/delete an issuer on the badgr account
   *
   * @param string $access_token
   * @param string $entity_id
   * @param string|NULL $method
   * @param array|NULL $_post_details
   * @param int $badgr_account_id
   *
   * @return mixed
   * @throws \GuzzleHttp\Exception\GuzzleException
   */
  public function badgr_update_rud_badges(string $access_token, string $entity_id, string $method = NULL, array $_post_details = NULL, int $badgr_account_id) {
    if (!$this->badgr_user_authenticate($access_token)) {
      $this->reauthenticate_token_badgr_account($access_token, $badgr_account_id);
    }

    $_headers = $this->badgr_set_header($access_token);

    try {
      $api_url = BADGR_BADGECLASS . '/' . $entity_id;

      if ($method == 'PUT' && !empty($_post_details)) {
        $request = $this->httpClient->request($method, $api_url, [
          'verify' => true,
          'form_params' => $_post_details,
          'headers' => $_headers
        ]);
      }
      elseif ($method == 'DELETE') {
        $request = $this->httpClient->request($method, $api_url, [
          'verify' => true,
          'headers' => $_headers
        ]);
      }
      else {
        $request = $this->httpClient->request('GET', $api_url, [
          'verify' => true,
          'headers' => $_headers
        ]);
      }

      $badges_data = Json::decode($request->getBody()->getContents());
    }
    catch (RequestException $e) {
      //An error happened.
      if ($e->hasResponse()) {
        watchdog_exception('badgr_badge', $e);
      }
    }

    return $badges_data;
  }

  /**
   * Award badges on the badgr account
   *
   * @param string $access_token
   * @param string $_post_details
   * @param string $entity_id
   * @param int $badgr_account_id
   *
   * @return mixed
   * @throws \GuzzleHttp\Exception\GuzzleException
   */
  public function badgr_award_badges(string &$access_token, string $_post_details, string $entity_id, int $badgr_account_id) {
    if (!$this->badgr_user_authenticate($access_token)) {
      $this->reauthenticate_token_badgr_account($access_token, $badgr_account_id);
    }
    $badges_data = NULL;
    $_headers = $this->badgr_set_header($access_token);

    try {
      $api_url = BADGR_BADGECLASS . '/' . $entity_id . '/assertions';

      $request = $this->httpClient->request('POST', $api_url, [
        'verify' => true,
        'body' => $_post_details,
        'headers' => $_headers
      ]);

      $badges_data = Json::decode($request->getBody()->getContents());
    }
    catch (RequestException $e) {
      //An error happened.
      if ($e->hasResponse()) {
        watchdog_exception('badgr_badge', $e);
      }
    }

    return $badges_data;
  }

  /**
   * To get list of badges on the badgr account
   *
   * @param string $access_token
   * @param int $badgr_account_id
   * @param string $entity_id
   * @param string $recipient
   *
   * @return mixed
   * @throws \GuzzleHttp\Exception\GuzzleException
   */
  public function badgr_get_award_badges(string &$access_token, int $badgr_account_id, string $entity_id, string $recipient) {
    if (!$this->badgr_user_authenticate($access_token)) {
      $this->reauthenticate_token_badgr_account($access_token, $badgr_account_id);
    }

    $_headers = $this->badgr_set_header($access_token);

    try {
      $api_url = BADGR_BADGECLASS . '/' . $entity_id . '/assertions?recipient=' . $recipient;
      $request = $this->httpClient->request('GET', $api_url, [
        'verify' => true,
        'headers' => $_headers
      ]);

      $all_awarded_badges = Json::decode($request->getBody()->getContents());
    }
    catch (RequestException $e) {
      //An error happened.
      if ($e->hasResponse()) {
        watchdog_exception('badgr_badge', $e);
      }
    }

    return $all_awarded_badges;
  }
}

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

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