Passed
Push — main ( 16966e...d887ef )
by Dylan
02:47
created

Connector::getAuthDomain()   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;
4
5
require_once __DIR__ . DIRECTORY_SEPARATOR . 'includes' . DIRECTORY_SEPARATOR . 'functions.php';
6
7
use Lifeboat\Exceptions\BadMethodException;
8
use Lifeboat\Exceptions\OAuthException;
9
use Lifeboat\Factory\ServiceFactory;
10
use Lifeboat\Services\ApiService;
11
use Lifeboat\Utils\Curl;
12
use Lifeboat\Utils\URL;
13
14
/**
15
 * Class Connector
16
 * @package Lifeboat
17
 *
18
 * @property string $_auth_domain
19
 * @property string|null $_access_token
20
 * @property string $_site_key
21
 *
22
 * // Services
23
 * @property \Lifeboat\Services\Orders $orders
24
 * @property \Lifeboat\Services\Addresses $addresses
25
 * @property \Lifeboat\Services\Customers $customers
26
 * @property \Lifeboat\Services\Collections $collections
27
 * @property \Lifeboat\Services\Pages $pages
28
 * @property \Lifeboat\Services\CustomPages $custom_pages
29
 * @property \Lifeboat\Services\DeliveryZones $delivery_zones
30
 * @property \Lifeboat\Services\TaxCodes $tax_codes
31
 * @property \Lifeboat\Services\Locations $locations
32
 * @property \Lifeboat\Services\Media $media
33
 * @property \Lifeboat\Services\Products $products
34
 */
35
abstract class Connector {
36
37
    const AUTH_DOMAIN   = 'https://accounts.lifeboat.app';
38
    const SITES_URL     = '/oauth/sites';
39
40
    const ACTIVE_HOST_PARAM = 'lb_active_host';
41
    const ACTIVE_KEY_PARAM  = 'lb_active_site_key';
42
43
    protected $_auth_domain = 'https://accounts.lifeboat.app';
44
    protected $_access_token = '';
45
    protected $_site_key = '';
46
    protected $_host = '';
47
48
    /**
49
     * @return string
50
     *
51
     * @throws OAuthException
52
     */
53
    abstract public function getAccessToken(): string;
54
55
    /**
56
     * @return string
57
     */
58
    public function getAuthDomain(): string
59
    {
60
        return $this->_auth_domain;
61
    }
62
63
    /**
64
     * @param string $service
65
     * @return ApiService|null
66
     * @throws BadMethodException
67
     */
68
    public function __get(string $service): ?ApiService
69
    {
70
        $obj = ServiceFactory::inst($this, $service);
71
        if (!$obj) throw new BadMethodException("Service for `{$service}` does not exist");
72
73
        return $obj;
74
    }
75
76
    /**
77
     * @return array
78
     * @throws OAuthException
79
     */
80
    public function getSites(): array
81
    {
82
        $curl = new Curl($this->auth_url(self::SITES_URL), [
83
            'access_token' => $this->getAccessToken()
84
        ]);
85
86
        $curl->setMethod('POST');
87
        $response = $curl->curl();
88
89
        if (!$response->isValid()) {
90
            $error = $response->getJSON();
91
            throw new OAuthException($error['error'], $error['code']);
92
        }
93
94
        return $response->getJSON() ?? [];
95
    }
96
97
    /**
98
     * Makes a request to the API to refresh the current access token
99
     *
100
     * @return $this
101
     * @throws OAuthException
102
     */
103
    public function refreshAccessToken(): Connector
104
    {
105
        $curl = new Curl($this->auth_url('/oauth/refresh_token'), [
106
            'access_token'  => $this->getAccessToken(),
107
        ]);
108
109
        $curl->setMethod('POST');
110
        $response = $curl->curl();
111
        $json = $response->getJSON();
112
113
        if (!$response->isValid() || !$json || !array_key_exists('access_token', $json)) {
114
            throw new OAuthException($response->getError());
115
        } else {
116
            $this->setAccessToken($json['access_token']);
0 ignored issues
show
Bug introduced by
The method setAccessToken() does not exist on Lifeboat\Connector. It seems like you code against a sub-type of Lifeboat\Connector such as Lifeboat\App. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

116
            $this->/** @scrutinizer ignore-call */ 
117
                   setAccessToken($json['access_token']);
Loading history...
117
        }
118
119
        return $this;
120
    }
121
122
    /**
123
     * @param string $host
124
     * @param string $site_key
125
     * @return $this
126
     */
127
    public function setActiveSite(string $host, string $site_key): Connector
128
    {
129
        $this->_host        = $host;
130
        $this->_site_key    = $site_key;
131
132
        if (session_status() === PHP_SESSION_ACTIVE) {
133
            $_SESSION[self::ACTIVE_HOST_PARAM]  = $this->_host;
134
            $_SESSION[self::ACTIVE_KEY_PARAM]   = $this->_site_key;
135
        }
136
137
        return $this;
138
    }
139
140
    /**
141
     * @param bool $check_session
142
     * @return array|null
143
     */
144
    public function getActiveSite(bool $check_session = true): ?array
145
    {
146
        if ($this->_host && $this->_site_key) {
147
            return ['host' => $this->_host, 'site_key' => $this->_site_key];
148
        }
149
150
        if ($check_session && session_status() === PHP_SESSION_ACTIVE) {
151
            $this->setActiveSite(
152
                $_SESSION[self::ACTIVE_HOST_PARAM] ?? '',
153
                $_SESSION[self::ACTIVE_KEY_PARAM] ?? ''
154
            );
155
156
            return $this->getActiveSite(false);
157
        }
158
159
        return null;
160
    }
161
162
    /**
163
     * @return string|null
164
     */
165
    public function getHost(): ?string
166
    {
167
        if (!$this->getActiveSite(true)) return null;
168
        return $this->_host;
169
    }
170
171
    /**
172
     * @return string|null
173
     */
174
    public function getSiteKey(): ?string
175
    {
176
        if (!$this->getActiveSite(true)) return null;
177
        return $this->_site_key;
178
    }
179
180
    /**
181
     * @param string $url
182
     * @param string $method
183
     * @param array $data
184
     * @param array $headers
185
     * @return CurlResponse
186
     * @throws OAuthException
187
     */
188
    public function curl_api(string $url, string $method = 'GET', array $data = [], array $headers = []): CurlResponse
189
    {
190
        $url = URL::is_absolute_url($url) ? $url
191
            : 'https://' . rtrim($this->getHost(), '/') . '/' . ltrim($url, '/');
0 ignored issues
show
Bug introduced by
It seems like $this->getHost() can also be of type null; however, parameter $string of rtrim() does only seem to accept string, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

191
            : 'https://' . rtrim(/** @scrutinizer ignore-type */ $this->getHost(), '/') . '/' . ltrim($url, '/');
Loading history...
192
193
        $curl = new Curl($url, $data, $headers);
194
195
        $curl->setMethod($method);
196
        $curl->addHeader('access-token', $this->getAccessToken());
197
        $curl->addHeader('site-key', $this->getSiteKey());
0 ignored issues
show
Bug introduced by
It seems like $this->getSiteKey() can also be of type null; however, parameter $value of Lifeboat\Utils\Curl::addHeader() does only seem to accept string, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

197
        $curl->addHeader('site-key', /** @scrutinizer ignore-type */ $this->getSiteKey());
Loading history...
198
        $curl->addHeader('Host', $this->getHost());
199
        $curl->addHeader('Accept', 'application/json');
200
201
        return $curl->curl_json();
202
    }
203
204
    /**
205
     * @param string $path
206
     * @return string
207
     */
208
    protected function auth_url(string $path): string
209
    {
210
        return rtrim($this->_auth_domain, '/') . '/' . ltrim($path, '/');
211
    }
212
}
213