Passed
Pull Request — 1.11.x (#4549)
by Angel Fernando Quiroz
12:43 queued 03:13
created

Api2RequestTrait   A

Complexity

Total Complexity 11

Size/Duplication

Total Lines 57
Duplicated Lines 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
wmc 11
eloc 36
c 1
b 0
f 0
dl 0
loc 57
rs 10

1 Method

Rating   Name   Duplication   Size   Complexity  
B send() 0 52 11
1
<?php
2
3
/* For licensing terms, see /license.txt */
4
5
namespace Chamilo\PluginBundle\Zoom\API;
6
7
use Exception;
8
9
trait Api2RequestTrait
10
{
11
    /**
12
     * @throws Exception
13
     */
14
    public function send($httpMethod, $relativePath, $parameters = [], $requestBody = null): string
15
    {
16
        $options = [
17
            CURLOPT_CUSTOMREQUEST => $httpMethod,
18
            CURLOPT_ENCODING => '',
19
            CURLOPT_HTTPHEADER => [
20
                'authorization: Bearer '.$this->token,
21
                'content-type: application/json',
22
            ],
23
            CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
24
            CURLOPT_MAXREDIRS => 10,
25
            CURLOPT_RETURNTRANSFER => true,
26
            CURLOPT_TIMEOUT => 30,
27
        ];
28
        if (!is_null($requestBody)) {
29
            $jsonRequestBody = json_encode($requestBody);
30
            if (false === $jsonRequestBody) {
31
                throw new Exception('Could not generate JSON request body');
32
            }
33
            $options[CURLOPT_POSTFIELDS] = $jsonRequestBody;
34
        }
35
36
        $url = "https://api.zoom.us/v2/$relativePath";
37
        if (!empty($parameters)) {
38
            $url .= '?'.http_build_query($parameters);
39
        }
40
        $curl = curl_init($url);
41
        if (false === $curl) {
42
            throw new Exception("curl_init returned false");
43
        }
44
        curl_setopt_array($curl, $options);
45
        $responseBody = curl_exec($curl);
46
        $responseCode = curl_getinfo($curl, CURLINFO_RESPONSE_CODE);
47
        $curlError = curl_error($curl);
48
        curl_close($curl);
49
50
        if ($curlError) {
51
            throw new Exception("cURL Error: $curlError");
52
        }
53
54
        if (false === $responseBody || !is_string($responseBody)) {
55
            throw new Exception('cURL Error');
56
        }
57
58
        if (empty($responseCode)
59
            || $responseCode < 200
60
            || $responseCode >= 300
61
        ) {
62
            throw new Exception($responseBody, $responseCode);
63
        }
64
65
        return $responseBody;
66
    }
67
}
68