moodlefetcher.php 1.72 KB
Newer Older
Francois Gannaz's avatar
Francois Gannaz committed
1
2
3
4
<?php

/**
 * @license http://www.gnu.org/licenses/gpl-3.0.html  GNU GPL v3
Francois Gannaz's avatar
Francois Gannaz committed
5
 * @copyright  2019 Université Grenoble Alpes
Francois Gannaz's avatar
Francois Gannaz committed
6
7
8
9
 */

namespace mod_labnbook\fetch;

Francois Gannaz's avatar
Francois Gannaz committed
10
11
12
13
14
/**
 * Integrate Moodle needs to the composed fetcher.
 * It fills data and actions for the communication with LabnBook through a fetcher.
 * It will be extended by 2 classes, for exchanges as a LnB institution or a LnB user.
 */
Francois Gannaz's avatar
Francois Gannaz committed
15
16
17
18
19
20
21
abstract class moodlefetcher
{
    /**
     * @var fetcher
     */
    protected $fetcher;

Francois Gannaz's avatar
Francois Gannaz committed
22
23
    public function __construct()
    {
Francois Gannaz's avatar
Francois Gannaz committed
24
25
26
27
28
29
30
31
        global $CFG;
        $this->fetcher = new fetcher(
            $CFG->labnbook_api_url,
            $this->getSigningKey(),
            $this->getEnvironment()
        );
    }

Francois Gannaz's avatar
Francois Gannaz committed
32
33
34
35
36
37
    public function getRedirectUrl(): string
    {
        global $CFG;
        return \rtrim($CFG->labnbook_api_url, '/') . '/v1/redirect';
    }

38
39
40
41
42
    public function getLastError(): ?\Stdclass
    {
        return $this->fetcher->getLastError();
    }

Francois Gannaz's avatar
Francois Gannaz committed
43
44
    protected function getEnvironment(): environment
    {
Francois Gannaz's avatar
Francois Gannaz committed
45
46
        global $CFG, $USER;
        $env = new environment();
47
        $env->orig = "inst"; // default value
Francois Gannaz's avatar
Francois Gannaz committed
48
49
50
51
52
        $env->iss = (int) $CFG->labnbook_institution_id;
        $env->sub = (int) $USER->id;
        return $env;
    }

Francois Gannaz's avatar
Francois Gannaz committed
53
54
    protected function fetch($verb, $path, $payload = [])
    {
Francois Gannaz's avatar
Francois Gannaz committed
55
56
57
58
        global $SESSION;
        $response = $this->fetcher->fetch($verb, $path, $payload);
        if (!empty($response->auth)) {
            if (empty($SESSION->labnbook)) {
Francois Gannaz's avatar
Francois Gannaz committed
59
                $SESSION->labnbook = new \Stdclass();
Francois Gannaz's avatar
Francois Gannaz committed
60
            }
61
            $SESSION->labnbook->auth = $response->auth;
Francois Gannaz's avatar
Francois Gannaz committed
62
63
64
65
        }
        return isset($response->data) ? $response->data : $response;
    }

Francois Gannaz's avatar
Francois Gannaz committed
66
    abstract protected function getSigningKey(): string;
Francois Gannaz's avatar
Francois Gannaz committed
67
}