Passed
Push — main ( 5be1cc...a3fefa )
by Dylan
01:51
created

Client::getAPISecret()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 1
eloc 1
c 1
b 0
f 0
nc 1
nop 0
dl 0
loc 3
rs 10
1
<?php
2
3
namespace Lifeboat\SDK;
4
5
use Lifeboat\SDK\Exceptions\OAuthException;
6
use Lifeboat\SDK\Services\Curl;
7
8
/**
9
 * Class Client
10
 * @package Lifeboat\SDK
11
 */
12
class Client {
13
14
    const AUTH_DOMAIN   = 'https://accounts.lifeboat.app';
15
    const TOKEN_URL     = self::AUTH_DOMAIN . '/oauth/api_token';
16
    const SITES_URL     = self::AUTH_DOMAIN . '/oauth/sites';
17
18
    private $_api_key = '';
19
    private $_api_secret = '';
20
    private $_access_token;
21
22
    public function __construct(string $_api_key, string $_api_secret)
23
    {
24
        $this->_api_key = $_api_key;
25
        $this->_api_secret = $_api_secret;
26
    }
27
28
    /**
29
     * Tries to fetch an access token from the API based on
30
     * the auth parameters available to client
31
     *
32
     * @return string
33
     * @throws OAuthException If any error is encountered during OAuth
34
     */
35
    public function getAccessToken(): string
36
    {
37
        if (!$this->_access_token) {
38
            $curl = new Curl(self::TOKEN_URL, [
39
                'api_key'       => $this->getAPIKey(),
40
                'api_secret'    => $this->getAPISecret()
41
            ]);
42
            
43
            $curl->setMethod('POST');
44
            $response = $curl->curl();
45
            
46
            if (!$response->isValid()) {
47
                throw new OAuthException($response->getError());
48
            }
49
            
50
            $json = $response->getJSON();
51
            if (!array_key_exists('access_token', $json)) {
52
                throw new OAuthException("Access token was not returned by API");   
53
            }
54
            
55
            $this->_access_token = $json['access_token'];
56
        }
57
58
        return $this->_access_token;
59
    }
60
61
    /**
62
     * Makes a request to the API to refresh the current access token
63
     * @see Client::getAccessToken()
64
     *
65
     * @return $this
66
     */
67
    public function refreshAccessToken(): Client
68
    {
69
        $this->_access_token = null;
70
        $this->getAccessToken();
71
        return $this;
72
    }
73
74
    /**
75
     * @return string
76
     */
77
    public function getAPIKey(): string
78
    {
79
        return $this->_api_key;
80
    }
81
82
    /**
83
     * @return string
84
     */
85
    public function getAPISecret(): string
86
    {
87
        return $this->_api_key;
88
    }
89
}
90