learnosity-1.0.x-dev/src/LearnositySdk.php

src/LearnositySdk.php
<?php

namespace Drupal\learnosity;

use LearnositySdk\Request\DataApi;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\HttpFoundation\RequestStack;
use Drupal\Core\Config\ConfigFactoryInterface;
use Drupal\Core\Extension\ModuleHandlerInterface;
use Drupal\Core\Logger\LoggerChannelFactoryInterface;
use LearnositySdk\Request\Init;
use LearnositySdk\Utils\Uuid;

/**
 * Wraps the Learnosity Sdk and utility classes.
 *
 * @package Drupal\learnosity.
 */
class LearnositySdk {

  /**
   * The service container.
   *
   * @var \Symfony\Component\DependencyInjection\ContainerInterface
   */
  protected $container;

  /**
   * Request stack.
   *
   * @var \Symfony\Component\HttpFoundation\Request
   */
  protected $request;

  /**
   * Configuration factory.
   *
   * @var \Drupal\Core\Config\ConfigFactoryInterface
   */
  protected $config;

  /**
   * Module handler service.
   *
   * @var \Drupal\Core\Extension\ModuleHandlerInterface
   */
  protected $moduleHandler;

  /**
   * The logger service.
   *
   * @var \Drupal\Core\Logger\LoggerChannelFactoryInterface
   */
  protected $logger;

  /**
   * Connection settings array.
   *
   * @var array
   */
  protected $connection = [];

  /**
   * LearnositySdk constructor.
   *
   * @param \Symfony\Component\DependencyInjection\ContainerInterface $container
   *   The container interface.
   * @param \Symfony\Component\HttpFoundation\RequestStack $request
   *   The request stack.
   * @param \Drupal\Core\Config\ConfigFactoryInterface $config_factory
   *   Config factory service.
   * @param \Drupal\Core\Extension\ModuleHandlerInterface $module_handler
   *   Module handler service.
   * @param \Drupal\Core\Logger\LoggerChannelFactoryInterface $logger
   *   The logger service.
   */
  public function __construct(ContainerInterface $container, RequestStack $request, ConfigFactoryInterface $config_factory, ModuleHandlerInterface $module_handler, LoggerChannelFactoryInterface $logger) {
    $this->container = $container;
    $this->request = $request->getCurrentRequest();
    $this->config = $config_factory->get('learnosity.settings');
    $this->moduleHandler = $module_handler;
    $this->logger = $logger;
    $this->setConnection($this->config->get('consumer_key'), $this->config->get('consumer_secret'));
  }

  /**
   * Fetch learnosity connection settings.
   *
   * @return array
   *   The connection settings.
   */
  public function getConnection() {
    return $this->connection;
  }

  /**
   * Set the learnosity connection settings.
   *
   * @param $key
   *   The consumer key.
   * @param $secret
   *   The consumer secret.
   */
  public function setConnection($key, $secret) {
    $this->connection = [
      'consumer_key' => $key,
      'consumer_secret' => $secret,
    ];
  }

  /**
   * Initialize this Learnosity service.
   *
   * @param string $service
   *   The service.
   * @param array $request
   *   An array of initialization parameters.
   * @param array $context
   *   The context from which this is being initialized.
   *
   * @return string
   *   The signed request json object used to initialize the Learnosity service.
   */
  public function init($service, array $request, array $context = []) {
    try {
      $security = [
        'consumer_key' => $this->connection['consumer_key'],
        'domain' => $this->getDomain(),
      ];

      // Allow modules to alter learnosity initialization.
      $this->moduleHandler->alter('learnosity_init', $request, $service, $context);

      // Remove any empty elements in the request.
      $request = array_filter($request);
      $init = new Init($service, $security, $this->connection['consumer_secret'], $request);
      return $init->generate();
    }
    catch (\Exception $e) {
      $this->logger->get('learnosity')->error($e->getMessage());
    }
  }

  /**
   * Performs a request against Learnosity's Data API.
   *
   * @param string $endpoint
   *   The api endpoint. (e.g v1/itembank/activities)
   * @param array $request
   *   Optional request packet of filter options and/or data.
   * @param mixed $action
   *   The action.
   * @param bool $recursive
   *   Toggle whether you wan to do a recursive call or not.
   * @param mixed $callback
   *   Optional callback if you don't want to return all at once.
   *
   * @return \LearnositySdk\Request\Remote
   *   The request response.
   */
  public function dataApi($endpoint, array $request = [], $action = NULL, $recursive = FALSE, $callback = NULL, $security = []) {
    try {
      // Build the data URL.
      $url = $this->getApiLibraryUrl('data') . '/' . $endpoint;

      $security = [
        'consumer_key' => $this->connection['consumer_key'],
        'domain' => $this->getDomain(),
      ];

      $dataApi = new DataApi();

      // If callback is set then this should be a recursive call.
      if ($recursive) {
        return $dataApi->requestRecursive($url, $security, $this->connection['consumer_secret'], $request, $action, $callback);
      }
      // Otherwise do a normal request.
      else {
        return $dataApi->request($url, $security, $this->connection['consumer_secret'], $request, $action);
      }
    }
    catch (\Exception $e) {
      $this->logger->get('learnosity')->error($e->getMessage());
    }
  }

  /**
   * Get the current site's domain.
   *
   * @return string
   *   The current domain.
   */
  public function getDomain() {
    return $this->request->getHost();
  }

  /**
   * Generate uuid.
   *
   * @param string $type
   *   The type of uuid algorithm (default is uuidv4).
   * @param null|string $namespace
   *   (Optional) The namespace identifier (used for version 3 and 5).
   * @param null|string $name
   *   (Optional) The name  (used for version 3 and 5).
   *
   * @return string
   *   The uuid.
   *
   * @throws \Exception
   */
  public function generateUuid($type = 'uuidv4', $namespace = NULL, $name = NULL) {
    return Uuid::generate($type, $namespace, $name);
  }

  /**
   * Fetches all Learnosity API service URL endpoints.
   *
   * @return array
   *   An array of Leanrosity API library URLs.
   */
  public function getApiLibraries() {
    return $this->container->getParameter('learnosity_api_libraries');
  }

  /**
   * Returns the Learnosity API service URL.
   *
   * @param string $service
   *   The service.
   *
   * @return string
   *   The Learnosity API service URL.
   */
  public function getApiLibraryUrl($service) {
    // Data has a slightly different URL structure.
    if ($service == 'data') {
      return $this->getApiLibraries()[$service] . '/' . $this->getApiVersion();
    }
    return $this->getApiLibraries()[$service] . '/?' . $this->getApiVersion();
  }

  /**
   * Returns the Learnosity service version.
   *
   * @return string
   *   The Learnosity API service version.
   */
  public function getApiVersion() {
    return $this->container->getParameter('learnosity_api_version');
  }

}

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

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