Test Failed
Push — main ( e6678b...02f88a )
by Dylan
09:26
created

Connector::getActiveSite()   A

Complexity

Conditions 5
Paths 3

Size

Total Lines 18
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 8
c 0
b 0
f 0
dl 0
loc 18
rs 9.6111
cc 5
nc 3
nop 1
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
 */
31
abstract class Connector {
32
33
    const AUTH_DOMAIN   = 'https://accounts.lifeboat.app';
34
    const SITES_URL     = '/oauth/sites';
35
36
    const ACTIVE_HOST_PARAM = 'lb_active_host';
37
    const ACTIVE_KEY_PARAM  = 'lb_active_site_key';
38
39
    protected string $_auth_domain = 'https://accounts.lifeboat.app';
40
    protected string $_access_token = '';
41
    protected string $_site_key = '';
42
    protected string $_host = '';
43
44
    /**
45
     * @return string
46
     *
47
     * @throws OAuthException
48
     */
49
    abstract public function getAccessToken(): string;
50
51
    /**
52
     * @param string $service
53
     * @return ApiService|null
54
     * @throws BadMethodException
55
     */
56
    public function __get(string $service): ?ApiService
57
    {
58
        $obj = ServiceFactory::inst($this, $service);
59
        if (!$obj) throw new BadMethodException("Service for `{$service}` does not exist");
60
61
        return $obj;
62
    }
63
64
    /**
65
     * @return array
66
     * @throws OAuthException
67
     */
68
    public function getSites(): array
69
    {
70
        $curl = new Curl($this->auth_url(self::SITES_URL), [
71
            'access_token' => $this->getAccessToken()
72
        ]);
73
74
        $curl->setMethod('POST');
75
        $response = $curl->curl();
76
77
        if (!$response->isValid()) {
78
            $error = $response->getJSON();
79
            throw new OAuthException($error['error'], $error['code']);
80
        }
81
82
        return $response->getJSON() ?? [];
83
    }
84
85
    /**
86
     * Makes a request to the API to refresh the current access token
87
     * @see Client::getAccessToken()
88
     *
89
     * @return $this
90
     * @throws OAuthException
91
     */
92
    public function refreshAccessToken(): Connector
93
    {
94
        $this->_access_token = null;
95
        $this->getAccessToken();
96
        return $this;
97
    }
98
99
    /**
100
     * @param string $host
101
     * @param string $site_key
102
     * @return $this
103
     */
104
    public function setActiveSite(string $host, string $site_key): Connector
105
    {
106
        $this->_host        = $host;
107
        $this->_site_key    = $site_key;
108
109
        if (session_status() === PHP_SESSION_ACTIVE) {
110
            $_SESSION[self::ACTIVE_HOST_PARAM]  = $this->_host;
111
            $_SESSION[self::ACTIVE_KEY_PARAM]   = $this->_site_key;
112
        }
113
114
        return $this;
115
    }
116
117
    /**
118
     * @param bool $check_session
119
     * @return array|null
120
     */
121
    public function getActiveSite(bool $check_session = true): ?array
122
    {
123
        if ($this->_host && $this->_site_key) {
124
            return ['host' => $this->_host, 'site_key' => $this->_site_key];
125
        }
126
127
        if ($check_session && session_status() === PHP_SESSION_ACTIVE) {
128
            $this->setActiveSite(
129
                $_SESSION[self::ACTIVE_HOST_PARAM] ?? '',
130
                $_SESSION[self::ACTIVE_KEY_PARAM] ?? ''
131
            );
132
133
            return $this->getActiveSite(false);
134
        }
135
136
137
138
        return null;
139
    }
140
141
    /**
142
     * @return string
143
     */
144
    public function getHost(): string
145
    {
146
        return $this->_host;
147
    }
148
149
    /**
150
     * @return string
151
     */
152
    public function getSiteKey(): string
153
    {
154
        return $this->_site_key;
155
    }
156
157
    /**
158
     * @param string $url
159
     * @param string $method
160
     * @param array $data
161
     * @param array $headers
162
     * @return CurlResponse
163
     * @throws OAuthException
164
     */
165
    public function curl_api(string $url, string $method = 'GET', array $data = [], array $headers = []): CurlResponse
166
    {
167
        $url = URL::is_absolute_url($url) ? $url
168
            : 'https://' . rtrim($this->getHost(), '/') . '/' . ltrim($url, '/');
169
170
        $curl = new Curl($url, $data, $headers);
171
172
        $curl->setMethod($method);
173
        $curl->addHeader('access-token', $this->getAccessToken());
174
        $curl->addHeader('site-key', $this->getSiteKey());
175
        $curl->addHeader('Host', $this->getHost());
176
        $curl->addHeader('Accept', 'application/json');
177
178
        return $curl->curl_json();
179
    }
180
181
    /**
182
     * @param string $path
183
     * @return string
184
     */
185
    protected function auth_url(string $path): string
186
    {
187
        return rtrim($this->_auth_domain, '/') . '/' . ltrim($path, '/');
188
    }
189
}
190