Client::refreshToken()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 8

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 8
rs 10
c 0
b 0
f 0
cc 1
nc 1
nop 0
1
<?php
2
3
namespace TarfinLabs\Iys;
4
5
use Illuminate\Support\Facades\Http;
6
7
class Client
8
{
9
    public $url;
10
    public $token;
11
    public $refreshToken;
12
13
    public function __construct()
14
    {
15
        $config = config('laravel-iys');
16
17
        $this->url = $config['url'];
18
19
        $this->authenticate();
20
    }
21
22
    protected function authenticate()
23
    {
24
        if (!$this->token) {
25
            $response = $this->getToken();
26
27
            $this->token = $response['accessToken'];
28
            $this->refreshToken = $response['refreshToken'];
29
        }
30
    }
31
32
    protected function getToken()
33
    {
34
        $response = Http::post($this->url . '/oauth2/token', [
35
            'username'   => config('laravel-iys.username'),
36
            'password'   => config('laravel-iys.password'),
37
            'grant_type' => 'password',
38
        ]);
39
40
        $response->throw();
41
42
        return $response;
43
    }
44
45
    protected function refreshToken()
46
    {
47
        $response = Http::post($this->url . '/oauth/token', [
48
            'refreshToken'   => $this->refreshToken,
49
        ]);
50
51
        $response->throw();
52
    }
53
54
    public function postJson($endpoint, $params)
55
    {
56
        $response = Http::withToken($this->token)->post($this->url . $endpoint, $params);
57
58
        return $response->throw()->json();
59
    }
60
61
    public function putJson($endpoint, $params)
62
    {
63
        $response = Http::withToken($this->token)->put($this->url . $endpoint, $params);
64
65
        return $response->throw()->json();
66
    }
67
68
    public function getJson($endpoint, $params = null)
69
    {
70
        $response = Http::withToken($this->token)->get($this->url . $endpoint, $params);
71
72
        return $response->throw()->json();
73
    }
74
75
    public function deleteJson($endpoint, $params = null)
76
    {
77
        $response = Http::withToken($this->token)->delete($this->url . $endpoint, $params);
78
79
        return $response->throw()->json();
80
    }
81
}
82