Passed
Push — main ( dd7998...bae415 )
by Dylan
03:01
created

Client::getAccessToken()   A

Complexity

Conditions 4
Paths 4

Size

Total Lines 24
Code Lines 13

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 13
c 0
b 0
f 0
dl 0
loc 24
rs 9.8333
cc 4
nc 4
nop 0
1
<?php
2
3
namespace Lifeboat;
4
5
use Lifeboat\Exceptions\OAuthException;
6
use Lifeboat\Utils\Curl;
7
8
/**
9
 * Class Client
10
 * @package Lifeboat
11
 *
12
 * @property string $_api_key
13
 * @property string $_api_secret
14
 */
15
class Client extends Connector {
16
17
    private $_api_key = '';
18
    private $_api_secret = '';
19
20
    public function __construct(string $_api_key, string $_api_secret, $_auth_domain = self::AUTH_DOMAIN)
21
    {
22
        $this->_api_key = $_api_key;
23
        $this->_api_secret = $_api_secret;
24
        $this->_auth_domain = rtrim($_auth_domain, '/');
25
    }
26
27
    /**
28
     * Tries to fetch an access token from the API based on
29
     * the auth parameters available to client
30
     *
31
     * @return string
32
     * @throws OAuthException If any error is encountered during OAuth
33
     */
34
    public function getAccessToken(): string
35
    {
36
        if (!$this->_access_token) {
37
            $curl = new Curl($this->auth_url(self::TOKEN_URL), [
38
                'api_key'       => $this->getAPIKey(),
39
                'api_secret'    => $this->getAPISecret()
40
            ]);
41
42
            $curl->setMethod('POST');
43
            $response = $curl->curl();
44
45
            if (!$response->isValid()) {
46
                throw new OAuthException($response->getRaw());
47
            }
48
49
            $json = $response->getJSON();
50
            if (!array_key_exists('access_token', $json)) {
51
                throw new OAuthException("Access token was not returned by API");
52
            }
53
54
            $this->_access_token = $json['access_token'];
55
        }
56
57
        return $this->_access_token;
58
    }
59
60
    /**
61
     * @return string
62
     */
63
    public function getAPIKey(): string
64
    {
65
        return $this->_api_key;
66
    }
67
68
    /**
69
     * @return string
70
     */
71
    public function getAPISecret(): string
72
    {
73
        return $this->_api_secret;
74
    }
75
}
76