http_client.php 935 Bytes
Newer Older
1
2
3
4
<?php

namespace local_asystgrade\api;

5
6
use Exception;

7
8
9
defined('MOODLE_INTERNAL') || die();

class http_client implements http_client_interface {
10
11
12
13
14
15
16
17
18

    /**
     * @param string $url
     * @param array $data
     * @return bool|string
     * @throws Exception
     */
    public function post(string $url, array $data): bool|string
    {
19
20
21
22
23
24
25
26
        $ch = curl_init($url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
        $response = curl_exec($ch);

        if (curl_errno($ch)) {
27
            throw new Exception('Curl error: ' . curl_error($ch));
28
29
30
31
32
        }

        curl_close($ch);

        if ($response === false) {
33
            throw new Exception('Error sending data to API');
34
35
36
37
38
        }

        return $response;
    }
}