client.php 1.28 KB
Newer Older
1
2
3
4
<?php

namespace local_asystgrade\api;

5
use Exception;
6
use \local_asystgrade\api\http_client_interface;
7

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

class client {
11
12
13
    private string                $endpoint;
    private http_client_interface $httpClient;
    private static ?client        $instance = null;
14

15
16
    /**
     * @param string $endpoint
17
     * @param http_client_interface $httpClient
18
     */
19
    private function __construct(string $endpoint, http_client_interface $httpClient) {
20
        $this->endpoint = $endpoint;
21
22
23
24
25
26
27
28
29
30
31
32
33
34
        $this->httpClient = $httpClient;
    }

    /**
     * @param string $endpoint
     * @param http_client_interface $httpClient
     * @return client
     */
    public static function getInstance(string $endpoint, http_client_interface $httpClient): client
    {
        if (self::$instance === null) {
            self::$instance = new client($endpoint, $httpClient);
        }
        return self::$instance;
35
36
    }

37
38
39
40
41
    /**
     * @param array $data
     * @return bool|string
     * @throws Exception
     */
42
43
44
45
46
47
48
    public function send_data(array $data): bool|string
    {
        try {
            return $this->httpClient->post($this->endpoint, $data);
        } catch (Exception $e) {
            throw new Exception('HTTP request error: ' . $e->getMessage());
        }
49
50
    }
}