Completed
Push — master ( 506c79...7daaad )
by Julito
12:09
created

ApiRequest::createEnrollment()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 14
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 1
eloc 9
c 1
b 0
f 0
nc 1
nop 3
dl 0
loc 14
rs 9.9666
1
<?php
2
/* For licensing terms, see /license.txt */
3
4
namespace Chamilo\PluginBundle\WhispeakAuth\Request;
5
6
use Chamilo\UserBundle\Entity\User;
7
use GuzzleHttp\Client;
8
use GuzzleHttp\Exception\RequestException;
9
10
/**
11
 * Class ApiRequest.
12
 *
13
 * @package Chamilo\PluginBundle\WhispeakAuth\Request
14
 */
15
class ApiRequest
16
{
17
    /**
18
     * @var \WhispeakAuthPlugin
19
     */
20
    protected $plugin;
21
    /**
22
     * @var string
23
     */
24
    protected $apiKey;
25
26
    /**
27
     * BaseController constructor.
28
     */
29
    public function __construct()
30
    {
31
        $this->plugin = \WhispeakAuthPlugin::create();
32
        $this->apiKey = $this->plugin->get(\WhispeakAuthPlugin::SETTING_TOKEN);
33
    }
34
35
    /**
36
     * Create a session token to perform an enrollment.
37
     *
38
     * @throws \Exception
39
     *
40
     * @return array
41
     */
42
    public function createEnrollmentSessionToken(User $user)
43
    {
44
        $apiKey = $this->plugin->get(\WhispeakAuthPlugin::SETTING_TOKEN);
45
        $langIso = api_get_language_isocode($user->getLanguage());
46
47
        return $this->sendRequest(
48
            'get',
49
            'enroll',
50
            $apiKey,
51
            $langIso
52
        );
53
    }
54
55
    /**
56
     * @param string $token
57
     * @param string $audioFilePath
58
     *
59
     * @throws \Exception
60
     *
61
     * @return array
62
     */
63
    public function createEnrollment($token, $audioFilePath, User $user)
64
    {
65
        $langIso = api_get_language_isocode($user->getLanguage());
66
67
        return $this->sendRequest(
68
            'post',
69
            'enroll',
70
            $token,
71
            $langIso,
72
            [
73
                [
74
                    'name' => 'file',
75
                    'contents' => fopen($audioFilePath, 'r'),
76
                    'filename' => basename($audioFilePath),
77
                ],
78
            ]
79
        );
80
    }
81
82
    /**
83
     * @throws \Exception
84
     *
85
     * @return array
86
     */
87
    public function createAuthenticationSessionToken(User $user = null)
88
    {
89
        $apiKey = $this->plugin->get(\WhispeakAuthPlugin::SETTING_TOKEN);
90
91
        $langIso = api_get_language_isocode($user ? $user->getLanguage() : null);
92
93
        return $this->sendRequest(
94
            'get',
95
            'auth',
96
            $apiKey,
97
            $langIso
98
        );
99
    }
100
101
    /**
102
     * @param string $token
103
     * @param string $audioFilePath
104
     *
105
     * @throws \Exception
106
     *
107
     * @return bool
108
     */
109
    public function performAuthentication($token, User $user, $audioFilePath)
110
    {
111
        $wsid = \WhispeakAuthPlugin::getAuthUidValue($user->getId());
112
113
        if (empty($wsid)) {
114
            throw new \Exception($this->plugin->get_lang('SpeechAuthNotEnrolled'));
115
        }
116
117
        $langIso = api_get_language_isocode($user ? $user->getLanguage() : null);
0 ignored issues
show
introduced by
$user is of type Chamilo\UserBundle\Entity\User, thus it always evaluated to true.
Loading history...
118
119
        try {
120
            $this->sendRequest(
121
                'post',
122
                'auth',
123
                $token,
124
                $langIso,
125
                [
126
                    [
127
                        'name' => 'speaker',
128
                        'contents' => $wsid->getValue(),
129
                    ],
130
                    [
131
                        'name' => 'file',
132
                        'contents' => fopen($audioFilePath, 'r'),
133
                        'filename' => basename($audioFilePath),
134
                    ],
135
                ]
136
            );
137
138
            return true;
139
        } catch (\Exception $e) {
140
            return false;
141
        }
142
    }
143
144
    /**
145
     * @param string $method
146
     * @param string $uri
147
     * @param string $authBearer
148
     * @param string $lang
149
     *
150
     * @throws \Exception
151
     *
152
     * @return array
153
     */
154
    private function sendRequest($method, $uri, $authBearer, $lang, array $multipart = [])
155
    {
156
        $httpClient = new Client(['base_uri' => $this->plugin->getApiUrl()]);
157
158
        try {
159
            $responseBody = $httpClient
160
                ->request(
161
                    $method,
162
                    $uri,
163
                    [
164
                        'headers' => [
165
                            'Authorization' => "Bearer $authBearer",
166
                            'Accept-Language' => $lang,
167
                        ],
168
                        'multipart' => $multipart,
169
                    ]
170
                )
171
                ->getBody()
172
                ->getContents();
173
174
            return json_decode($responseBody, true);
175
        } catch (RequestException $requestException) {
176
            if (!$requestException->hasResponse()) {
177
                throw new \Exception($requestException->getMessage());
178
            }
179
180
            $responseBody = $requestException->getResponse()->getBody()->getContents();
181
            $json = json_decode($responseBody, true);
182
183
            if (empty($json['message'])) {
184
                throw new \Exception($requestException->getMessage());
185
            }
186
187
            $message = is_array($json['message']) ? implode(PHP_EOL, $json['message']) : $json['message'];
188
189
            throw new \Exception($message);
190
        } catch (Exception $exception) {
0 ignored issues
show
Bug introduced by
The type Chamilo\PluginBundle\Whi...kAuth\Request\Exception was not found. Did you mean Exception? If so, make sure to prefix the type with \.
Loading history...
191
            throw new \Exception($exception->getMessage());
192
        }
193
    }
194
}
195