Issues (2160)

plugin/whispeakauth/Request/ApiRequest.php (3 issues)

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
     * @throws \Exception
103
     *
104
     * @return array
105
     */
106
    public function deleteEnrollment(User $user)
107
    {
108
        $apiKey = $this->plugin->get(\WhispeakAuthPlugin::SETTING_TOKEN);
109
        $langIso = api_get_language_isocode($user->getLanguage());
110
        $userAuthKey = \WhispeakAuthPlugin::getAuthUidValue($user->getId());
111
112
        if (empty($userAuthKey) || empty($userAuthKey->getValue())) {
113
            throw new \Exception(get_plugin_lang('NoEnrollment', 'WhispeakAuthPlugin'));
114
        }
115
116
        $queryData = ['speaker' => $userAuthKey->getValue()];
117
118
        return $this->sendRequest(
119
            'delete',
120
            'enroll',
121
            $apiKey,
122
            $langIso,
123
            [],
124
            $queryData
125
        );
126
    }
127
128
    /**
129
     * @param string $token
130
     * @param string $audioFilePath
131
     *
132
     * @throws \Exception
133
     *
134
     * @return bool
135
     */
136
    public function performAuthentication($token, User $user, $audioFilePath)
137
    {
138
        $wsid = \WhispeakAuthPlugin::getAuthUidValue($user->getId());
139
140
        if (empty($wsid)) {
141
            throw new \Exception($this->plugin->get_lang('SpeechAuthNotEnrolled'));
142
        }
143
144
        $langIso = api_get_language_isocode($user ? $user->getLanguage() : null);
0 ignored issues
show
$user is of type Chamilo\UserBundle\Entity\User, thus it always evaluated to true.
Loading history...
145
146
        $this->sendRequest(
147
            'post',
148
            'auth',
149
            $token,
150
            $langIso,
151
            [
152
                [
153
                    'name' => 'speaker',
154
                    'contents' => $wsid->getValue(),
155
                ],
156
                [
157
                    'name' => 'file',
158
                    'contents' => fopen($audioFilePath, 'r'),
159
                    'filename' => basename($audioFilePath),
160
                ],
161
            ]
162
        );
163
    }
164
165
    /**
166
     * @param string $method
167
     * @param string $uri
168
     * @param string $authBearer
169
     * @param string $lang
170
     * @param array  $queryParams
171
     *
172
     * @throws \GuzzleHttp\Exception\GuzzleException
173
     *
174
     * @return array
175
     */
176
    private function sendRequest($method, $uri, $authBearer, $lang, array $multipart = [], $queryParams = [])
177
    {
178
        $httpClient = new Client(['base_uri' => $this->plugin->getApiUrl()]);
179
180
        $options = [];
181
        $options['headers'] = [
182
            'Authorization' => "Bearer $authBearer",
183
            'Accept-Language' => $lang,
184
        ];
185
186
        if ($queryParams) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $queryParams of type array is implicitly converted to a boolean; are you sure this is intended? If so, consider using ! empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
187
            $options['query'] = $queryParams;
188
        } else {
189
            $options['multipart'] = $multipart;
190
        }
191
192
        try {
193
            $responseBody = $httpClient
194
                ->request(
195
                    $method,
196
                    $uri,
197
                    $options
198
                )
199
                ->getBody()
200
                ->getContents();
201
202
            return json_decode($responseBody, true);
203
        } catch (RequestException $requestException) {
204
            if (!$requestException->hasResponse()) {
205
                throw new \Exception($requestException->getMessage());
206
            }
207
208
            $responseBody = $requestException->getResponse()->getBody()->getContents();
209
            $json = json_decode($responseBody, true);
210
211
            $message = '';
212
213
            if (isset($json['asserts'])) {
214
                foreach ($json['asserts'] as $assert) {
215
                    if ('invalid_' === substr($assert['value'], 0, 8)) {
216
                        $message .= $assert['message'].PHP_EOL;
217
                    }
218
                }
219
            } elseif (empty($json['message'])) {
220
                $message = $requestException->getMessage();
221
            } else {
222
                $message = is_array($json['message']) ? implode(PHP_EOL, $json['message']) : $json['message'];
223
            }
224
225
            throw new \Exception($message);
226
        } catch (Exception $exception) {
0 ignored issues
show
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...
227
            throw new \Exception($exception->getMessage());
228
        }
229
    }
230
}
231