Chamilo is a learning management system focused on ease of use and accessibility
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 
 
chamilo-lms/plugin/whispeakauth/Request/ApiRequest.php

127 lines
3.2 KiB

<?php
/* For licensing terms, see /license.txt */
namespace Chamilo\PluginBundle\WhispeakAuth\Request;
use Chamilo\UserBundle\Entity\User;
use GuzzleHttp\Client;
use GuzzleHttp\Exception\RequestException;
/**
* Class ApiRequest.
*
* @package Chamilo\PluginBundle\WhispeakAuth\Request
*/
class ApiRequest
{
/**
* @var \WhispeakAuthPlugin
*/
protected $plugin;
/**
* @var string
*/
protected $apiKey;
/**
* BaseController constructor.
*/
public function __construct()
{
$this->plugin = \WhispeakAuthPlugin::create();
$this->apiKey = $this->plugin->get(\WhispeakAuthPlugin::SETTING_TOKEN);
}
/**
* Create a session token to perform an enrollment.
*
* @param \Chamilo\UserBundle\Entity\User $user
*
* @throws \Exception
*
* @return array
*/
public function createEnrollmentSessionToken(User $user)
{
$apiKey = $this->plugin->get(\WhispeakAuthPlugin::SETTING_TOKEN);
$langIso = api_get_language_isocode($user->getLanguage());
return $this->sendRequest(
'get',
'enroll',
$apiKey,
['lang' => $langIso]
);
}
/**
* @param string $token
* @param string $audioFilePath
*
* @throws \Exception
*
* @return array
*/
public function createEnrollment($token, $audioFilePath)
{
return $this->sendRequest(
'post',
'enroll',
$token,
[],
[
[
'name' => 'file',
'contents' => fopen($audioFilePath, 'r'),
'filename' => basename($audioFilePath),
],
]
);
}
/**
* @param string $method
* @param string $uri
* @param string $authBearer
* @param array $query
* @param array $multipart
*
* @throws \Exception
*
* @return array
*/
private function sendRequest($method, $uri, $authBearer, array $query = [], array $multipart = [])
{
$httpClient = new Client(['base_uri' => $this->plugin->getApiUrl()]);
try {
$responseBody = $httpClient
->request(
$method,
$uri,
[
'headers' => ['Authorization' => "Bearer $authBearer"],
'query' => $query,
'multipart' => $multipart,
]
)
->getBody()
->getContents();
return json_decode($responseBody, true);
} catch (RequestException $requestException) {
if (!$requestException->hasResponse()) {
throw new \Exception($requestException->getMessage());
}
$responseBody = $requestException->getResponse()->getBody()->getContents();
$json = json_decode($responseBody, true);
$message = is_array($json['message']) ? implode(PHP_EOL, $json['message']) : $json['message'];
throw new \Exception($message);
} catch (Exception $exception) {
throw new \Exception($exception->getMessage());
}
}
}