edulegit_client::fetch()   A
last analyzed

Complexity

Conditions 3
Paths 4

Size

Total Lines 37
Code Lines 26

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 26
c 1
b 0
f 0
dl 0
loc 37
rs 9.504
cc 3
nc 4
nop 3
1
<?php
2
// This file is part of Moodle - http://moodle.org/
3
//
4
// Moodle is free software: you can redistribute it and/or modify
5
// it under the terms of the GNU General Public License as published by
6
// the Free Software Foundation, either version 3 of the License, or
7
// (at your option) any later version.
8
//
9
// Moodle is distributed in the hope that it will be useful,
10
// but WITHOUT ANY WARRANTY; without even the implied warranty of
11
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12
// GNU General Public License for more details.
13
//
14
// You should have received a copy of the GNU General Public License
15
// along with Moodle.  If not, see <http://www.gnu.org/licenses/>.
16
17
/**
18
 * The assignsubmission_edulegit API client class.
19
 *
20
 * Handles communication with the EduLegit API for Moodle assignments.
21
 *
22
 * @package   assignsubmission_edulegit
23
 * @author    Alex Crosby <[email protected]>
24
 * @copyright @2024 EduLegit.com
25
 * @license   http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
26
 */
27
28
namespace assignsubmission_edulegit;
29
30
/**
31
 * Class edulegit_client
32
 *
33
 * This class is responsible for sending requests to the EduLegit API and managing the API connection.
34
 */
35
class edulegit_client {
36
37
    /**
38
     * API authentication key.
39
     *
40
     * @var string
41
     */
42
    private string $authkey = '';
43
44
    /**
45
     * Base URL for the EduLegit API.
46
     *
47
     * @var string
48
     */
49
    private string $baseurl = 'https://api.edulegit.com';
50
51
    /**
52
     * Enables or disables debugging.
53
     *
54
     * @var bool
55
     */
56
    private bool $debug = true;
57
58
    /**
59
     * Constructor for the edulegit_client class.
60
     *
61
     * @param string $authkey The authentication key for API access.
62
     */
63
    public function __construct(string $authkey) {
64
        $this->authkey = $authkey;
65
    }
66
67
    /**
68
     * Sends a request to the EduLegit API.
69
     *
70
     * @param string $method The HTTP method to use (e.g., 'POST', 'GET').
71
     * @param string $uri The URI of the API endpoint.
72
     * @param array $data The data to be sent with the request.
73
     * @return edulegit_client_response The API response.
74
     */
75
    public function fetch(string $method, string $uri, array $data = []): edulegit_client_response {
76
        $url = $this->baseurl . $uri;
77
78
        $curl = curl_init($this->filter_url($url));
79
        curl_setopt($curl, CURLOPT_CUSTOMREQUEST, $method);
80
81
        $postfields = $this->build_post_fields($data);
82
        if ($postfields) {
83
            curl_setopt($curl, CURLOPT_POST, true);
84
            curl_setopt($curl, CURLOPT_POSTFIELDS, $postfields);
85
        }
86
        $headers = [
87
                'X-API-TOKEN' => $this->authkey,
88
                'Content-Type' => 'application/json',
89
                'User-Agent' => 'Mozilla/5.0 Edulegit plugin/1.0',
90
        ];
91
        curl_setopt($curl, CURLOPT_HTTPHEADER, $this->build_headers($headers));
92
93
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
94
        curl_setopt($curl, CURLOPT_FOLLOWLOCATION, true);
95
        curl_setopt($curl, CURLOPT_FAILONERROR, false);
96
        curl_setopt($curl, CURLOPT_ENCODING, '');
97
        curl_setopt($curl, CURLOPT_TIMEOUT, 10);
98
        curl_setopt($curl, CURLOPT_CONNECTTIMEOUT, 7);
99
100
        if ($this->debug) {
101
            curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
102
            curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
103
        }
104
105
        $body = curl_exec($curl);
106
        $info = curl_getinfo($curl);
107
        $error = curl_error($curl);
108
109
        curl_close($curl);
110
111
        return new edulegit_client_response((string) $body, (array) $info, (string) $error, $url);
112
    }
113
114
    /**
115
     * Filters and encodes a URL.
116
     *
117
     * @param string $url The URL to be filtered.
118
     * @return string The filtered URL.
119
     */
120
    private function filter_url(string $url) {
121
        return str_replace(
122
                ['%3A', '%2F', '%3F', '%3D', '%26', '%40', '%25', '%23'],
123
                [':', '/', '?', '=', '&', '@', '%', '#'],
124
                rawurlencode($url)
125
        );
126
    }
127
128
    /**
129
     * Builds the post fields for the cURL request.
130
     *
131
     * @param array $data The data to be encoded and sent.
132
     * @return string The JSON-encoded data.
133
     */
134
    private function build_post_fields(array $data) {
135
        return edulegit_helper::json_encode($data);
136
    }
137
138
    /**
139
     * Constructs the HTTP headers for the request.
140
     *
141
     * @param array $headers The array of headers (key-value pairs).
142
     * @return array The formatted headers.
143
     */
144
    protected function build_headers(array $headers) {
145
        $result = [];
146
        foreach ($headers as $key => $value) {
147
            $result[] = $key . ': ' . $value;
148
        }
149
        return $result;
150
    }
151
152
    /**
153
     * Initializes a Moodle assignment via the API.
154
     *
155
     * @param array $data The data to initialize the assignment.
156
     * @return edulegit_client_response The API response.
157
     */
158
    public function init_assignment($data): edulegit_client_response {
159
        return $this->fetch('POST', '/init-moodle-assignment', $data);
160
    }
161
}
162