Passed
Push — main ( 46fad3...57b898 )
by Leandro
01:28
created

MoodleRestApi::__construct()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 12
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Importance

Changes 2
Bugs 0 Features 0
Metric Value
eloc 8
c 2
b 0
f 0
dl 0
loc 12
rs 10
cc 3
nc 3
nop 4
1
<?php
2
3
namespace Puerari\Moodle;
4
5
/**
6
 * @class MoodleRestApi
7
 * @package Puerari\Moodle
8
 * @author Leandro Puerari <[email protected]>
9
 */
10
class MoodleRestApi
11
{
12
    /** Constant that defines return format to JSON */
13
    /*public*/
14
    const RETURN_JSON = 'json';
15
16
    /** Constant that defines return format to XML */
17
    /*public*/
18
    const RETURN_XML = 'xml';
19
20
    /** Constant that defines return format to ARRAY */
21
    /*public*/
22
    const RETURN_ARRAY = 'array';
23
24
    /** Constant that defines return format to ARRAY */
25
    /*public*/
26
    const METHOD_GET = 'get';
27
28
    /** Constant that defines return format to ARRAY */
29
    /*public*/
30
    const METHOD_POST = 'post';
31
32
    /** @var string Access Token */
33
    private $access_token;
34
35
    /** @var string URL for the Moodle server */
36
    private $server_url;
37
38
    /** @var string Return format for the response (json, array or xml) */
39
    private $return_format;
40
41
    /** @var bool defaults to false - Verify or not the SSL certificate */
42
    private $ssl_verify;
43
44
    /** @var array data to be passed to the API */
45
    private $data;
46
47
    /** use Traits */
48
    use Core/*, Server*/
49
        ;
50
51
    /** MoodleRestApi constructor.
52
     * @param string $server_url
53
     * @param string $access_token
54
     * @param string $return_format
55
     * @param bool $ssl_verify
56
     * @throws MraException
57
     */
58
    public function __construct(/*string*/ $server_url, /*string*/ $access_token, /*string*/ $return_format = MoodleRestApi::RETURN_ARRAY, /*bool*/ $ssl_verify = false)
59
    {
60
        if (!filter_var($server_url, FILTER_VALIDATE_URL))
61
            throw new MraException('Invalid URL!');
62
63
        $urllen = strlen($server_url) - 1;
64
        $url = ($server_url[$urllen] == "/") ? mb_substr($server_url, 0, $urllen) : $server_url;
65
66
        $this->server_url = $url . '/webservice/rest/server.php';
67
        $this->access_token = $access_token;
68
        $this->return_format = $return_format;
69
        $this->ssl_verify = $ssl_verify;
70
    }
71
72
    /**
73
     * @return string
74
     */
75
    public function getAccessToken()/*: string*/
76
    {
77
        return $this->access_token;
78
    }
79
80
    /**
81
     * @param string $access_token
82
     * @return MoodleRestApi
83
     */
84
    public function setAccessToken(/*string*/ $access_token)/*: MoodleRestApi*/
85
    {
86
        $this->access_token = $access_token;
87
        return $this;
88
    }
89
90
    /**
91
     * @return string
92
     */
93
    public function getServerUrl()/*: string*/
94
    {
95
        return $this->server_url;
96
    }
97
98
    /**
99
     * @param string $server_url
100
     * @return MoodleRestApi
101
     * @throws MraException
102
     */
103
    public function setServerUrl(/*string*/ $server_url)/*: MoodleRestApi*/
104
    {
105
        if (!filter_var($server_url, FILTER_VALIDATE_URL))
106
            throw new MraException('Invalid URL!');
107
108
        $this->server_url = $server_url;
109
        return $this;
110
    }
111
112
    /**
113
     * @return bool
114
     */
115
    public function getSslVerify()/*: bool*/
116
    {
117
        return $this->ssl_verify;
118
    }
119
120
    /**
121
     * @param bool $ssl_verify
122
     */
123
    public function setSslVerify(/*bool*/ $ssl_verify)/*: void*/
124
    {
125
        $this->ssl_verify = $ssl_verify;
126
    }
127
128
129
    /**
130
     * @return string
131
     */
132
    public function getReturnFormat()/*: string*/
133
    {
134
        return $this->return_format;
135
    }
136
137
    /**
138
     * @param string $return_format
139
     * @return MoodleRestApi
140
     * @throws MraException
141
     */
142
    public function setReturnFormat(/*string*/ $return_format)/*: MoodleRestApi*/
143
    {
144
        $valid_formats = [self::RETURN_XML, self::RETURN_JSON, self::RETURN_ARRAY];
145
        if (!in_array($return_format, $valid_formats)) {
146
            throw new MraException("Invalid return format: '$return_format'. Valid formats: " . implode(', ', $valid_formats));
147
        }
148
        $this->return_format = $return_format;
149
        return $this;
150
    }
151
152
    public function request(/*string*/ $wsfunction, array $parameters = [], $method = self::METHOD_GET)
153
    {
154
        $this->data = $parameters;
155
        $this->data['wsfunction'] = $wsfunction;
156
        if ($method == self::METHOD_GET) {
157
            return $this->execGetCurl();
158
        } else {
159
            return $this->execPostCurl();
160
        }
161
    }
162
163
    /**
164
     * @return array|string
165
     * @throws MraException
166
     */
167
    protected function execGetCurl()
168
    {
169
        $this->config();
170
        $url = $this->server_url . '?' . http_build_query($this->data);
171
        try {
172
            $ch = curl_init();
173
            curl_setopt($ch, CURLOPT_URL, $url);
174
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
175
            curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'GET');
176
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, $this->ssl_verify);
177
            $response = curl_exec($ch);
178
            curl_close($ch);
179
        } catch (\Exception $exception) {
180
            throw new MraException($exception->getMessage(), $exception->getCode());
181
        }
182
        return $this->formattedReturn($response);
183
    }
184
185
    /**
186
     * @return array|string
187
     * @throws MraException
188
     */
189
    protected function execPostCurl()
190
    {
191
        $this->config();
192
        $params['wstoken'] = $this->data['wstoken'];
0 ignored issues
show
Comprehensibility Best Practice introduced by
$params was never initialized. Although not strictly required by PHP, it is generally a good practice to add $params = array(); before regardless.
Loading history...
193
        $params['moodlewsrestformat'] = $this->data['moodlewsrestformat'];
194
        $params['wsfunction'] = $this->data['wsfunction'];
195
        $url = $this->server_url . '?' . http_build_query($params);
196
        unset($this->data['wstoken'], $this->data['moodlewsrestformat'], $this->data['wsfunction']);
197
198
        try {
199
            $ch = curl_init();
200
            curl_setopt($ch, CURLOPT_URL, $url);
201
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
202
            curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
203
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, $this->ssl_verify);
204
            curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($this->data));
205
            curl_setopt($ch, CURLOPT_POST, 1);
206
            $response = curl_exec($ch);
207
            curl_close($ch);
208
        } catch (\Exception $exception) {
209
            throw new MraException($exception->getMessage(), $exception->getCode());
210
        }
211
212
        return $this->formattedReturn($response);
213
    }
214
215
    private function config()/*: void*/
216
    {
217
        $this->data['wstoken'] = $this->access_token;
218
        if ($this->return_format == self::RETURN_ARRAY) {
219
            $this->data['moodlewsrestformat'] = self::RETURN_JSON;
220
        } else {
221
            $this->data['moodlewsrestformat'] = $this->return_format;
222
        }
223
    }
224
225
    /**
226
     * @param $response
227
     * @return array|string
228
     */
229
    private function formattedReturn(/*string*/ $response)/*: array*/
230
    {
231
        if ($this->return_format == self::RETURN_ARRAY) {
232
            $response = json_decode($response, true);
233
        }
234
        return $response;
235
    }
236
}
237