Completed
Push — d64 ( 4f8de5...da115c )
by Welling
02:13
created

BaseClientRemote::__construct()   B

Complexity

Conditions 5
Paths 16

Size

Total Lines 21
Code Lines 13

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 16
CRAP Score 5

Importance

Changes 0
Metric Value
cc 5
eloc 13
nc 16
nop 2
dl 0
loc 21
ccs 16
cts 16
cp 1
crap 5
rs 8.7624
c 0
b 0
f 0
1
<?php
2
3
/**
4
 * Directus – <http://getdirectus.com>
5
 *
6
 * @link      The canonical repository – <https://github.com/directus/directus>
7
 * @copyright Copyright 2006-2016 RANGER Studio, LLC – <http://rangerstudio.com>
8
 * @license   GNU General Public License (v3) – <http://www.gnu.org/copyleft/gpl.html>
9
 */
10
11
namespace Directus\SDK;
12
13
use Directus\SDK\Exception\UnauthorizedRequestException;
14
use Directus\Util\ArrayUtils;
15
use GuzzleHttp\Client as HTTPClient;
16
use GuzzleHttp\Exception\ClientException;
17
18
/**
19
 * Abstract Base Client Remote
20
 *
21
 * @author Welling Guzmán <[email protected]>
22
 */
23
abstract class BaseClientRemote extends AbstractClient
24
{
25
    /**
26
     * Directus base url
27
     *
28
     * @var string
29
     */
30
    protected $baseUrl = 'http://localhost';
31
32
    /**
33
     * Directus hosted base url format
34
     *
35
     * @var string
36
     */
37
    protected $hostedBaseUrlFormat = 'https://%s.directus.io';
38
39
    /**
40
     * Directus Server base endpoint
41
     *
42
     * @var string
43
     */
44
    protected $baseEndpoint;
45
46
    /**
47
     * API Version
48
     *
49
     * @var string
50
     */
51
    protected $apiVersion;
52
53
    /**
54
     * Directus Hosted endpoint format.
55
     *
56
     * @var string
57
     */
58
    protected $hostedBaseEndpointFormat;
59
60
    /**
61
     * Directus Hosted Instance Key
62
     *
63
     * @var int|string
64
     */
65
    protected $instanceKey;
66
67
    /**
68
     * Authentication Token
69
     *
70
     * @var string
71
     */
72
    protected $accessToken;
73
74
    /**
75
     * HTTP Client
76
     *
77
     * @var \GuzzleHttp\Client
78
     */
79
    protected $httpClient;
80
81
    /**
82
     * HTTP Client request timeout
83
     *
84
     * @var int
85
     */
86
    protected $timeout = 60;
87
88
    const BOOKMARKS_CREATE_ENDPOINT = 'bookmarks';
89
    const BOOKMARKS_READ_ENDPOINT = 'bookmarks/%s';
90
    const BOOKMARKS_DELETE_ENDPOINT = 'bookmarks/%s';
91
    const BOOKMARKS_ALL_ENDPOINT = 'bookmarks';
92
    const BOOKMARKS_USER_ENDPOINT = 'bookmarks/user/%s';
93
94
    const TABLE_ENTRIES_ENDPOINT = 'tables/%s/rows';
95
    const TABLE_ENTRY_ENDPOINT = 'tables/%s/rows/%s';
96
    const TABLE_ENTRY_CREATE_ENDPOINT = 'tables/%s/rows';
97
    const TABLE_ENTRY_UPDATE_ENDPOINT = 'tables/%s/rows/%s';
98
    const TABLE_ENTRY_DELETE_ENDPOINT = 'tables/%s/rows/%s';
99
    const TABLE_LIST_ENDPOINT = 'tables';
100
    const TABLE_INFORMATION_ENDPOINT = 'tables/%s';
101
    const TABLE_PREFERENCES_ENDPOINT = 'tables/%s/preferences';
102
    const TABLE_CREATE_ENDPOINT = 'privileges/1'; // ID not being used but required @TODO: REMOVE IT
103
    const TABLE_DELETE_ENDPOINT = 'tables/%s';
104
105
    const COLUMN_LIST_ENDPOINT = 'tables/%s/columns';
106
    const COLUMN_CREATE_ENDPOINT = 'tables/%s/columns';
107
    const COLUMN_DELETE_ENDPOINT = 'tables/%s/columns/%s';
108
    const COLUMN_INFORMATION_ENDPOINT = 'tables/%s/columns/%s';
109
    const COLUMN_OPTIONS_CREATE_ENDPOINT = 'tables/%s/columns/%s/%s';
110
111
    const GROUP_LIST_ENDPOINT = 'groups';
112
    const GROUP_CREATE_ENDPOINT = 'groups';
113
    const GROUP_INFORMATION_ENDPOINT = 'groups/%s';
114
    const GROUP_PRIVILEGES_ENDPOINT = 'privileges/%s';
115
    const GROUP_PRIVILEGES_CREATE_ENDPOINT = 'privileges/%s';
116
117
    const FILE_LIST_ENDPOINT = 'files';
118
    const FILE_CREATE_ENDPOINT = 'files';
119
    const FILE_UPDATE_ENDPOINT = 'files/%s';
120
    const FILE_INFORMATION_ENDPOINT = 'files/%s';
121
122
    const SETTING_LIST_ENDPOINT = 'settings';
123
    const SETTING_COLLECTION_ENDPOINT = 'settings/%s';
124
125
    const MESSAGES_CREATE_ENDPOINT = 'messages/rows';
126
    const MESSAGES_USER_ENDPOINT = 'messages/rows/%s';
127
128 38
    public function __construct($accessToken, $options = [])
129
    {
130 38
        $this->accessToken = $accessToken;
131
132 38
        if (isset($options['base_url'])) {
133 4
            $this->baseUrl = rtrim($options['base_url'], '/');
134 4
            $this->baseEndpoint = $this->baseUrl . '/api';
135 4
        }
136
137 38
        $instanceKey = isset($options['instance_key']) ? $options['instance_key'] : false;
138 38
        if ($instanceKey) {
139 2
            $this->instanceKey = $instanceKey;
140 2
            $this->baseUrl = sprintf($this->hostedBaseUrlFormat, $instanceKey);
141 2
            $this->baseEndpoint = $this->baseUrl . '/api';
142 2
        }
143
144 38
        $this->apiVersion = isset($options['version']) ? $options['version'] : 1;
145 38
        $this->baseEndpoint .= '/' . $this->getAPIVersion();
146
147 38
        $this->setHTTPClient($this->getDefaultHTTPClient());
148 38
    }
149
150
    /**
151
     * Get the base endpoint url
152
     *
153
     * @return string
154
     */
155 4
    public function getBaseEndpoint()
156
    {
157 4
        return $this->baseEndpoint;
158
    }
159
160
    /**
161
     * Get the base url
162
     *
163
     * @return string
164
     */
165 2
    public function getBaseUrl()
166
    {
167 2
        return $this->baseUrl;
168
    }
169
170
    /**
171
     * Get API Version
172
     *
173
     * @return int|string
174
     */
175 38
    public function getAPIVersion()
176
    {
177 38
        return $this->apiVersion;
178
    }
179
180
    /**
181
     * Get the authentication access token
182
     *
183
     * @return string
184
     */
185 2
    public function getAccessToken()
186
    {
187 2
        return $this->accessToken;
188
    }
189
190
    /**
191
     * Set a new authentication access token
192
     *
193
     * @param $newAccessToken
194
     */
195 2
    public function setAccessToken($newAccessToken)
196
    {
197 2
        $this->accessToken = $newAccessToken;
198 2
    }
199
200
    /**
201
     * Get the Directus hosted instance key
202
     *
203
     * @return null|string
204
     */
205 4
    public function getInstanceKey()
206
    {
207 4
        return $this->instanceKey;
208
    }
209
210
    /**
211
     * Set the HTTP Client
212
     *
213
     * @param HTTPClient $httpClient
214
     */
215 38
    public function setHTTPClient(HTTPClient $httpClient)
216
    {
217 38
        $this->httpClient = $httpClient;
218 38
    }
219
220
    /**
221
     * Get the HTTP Client
222
     *
223
     * @return HTTPClient|null
224
     */
225 38
    public function getHTTPClient()
226
    {
227 38
        return $this->httpClient;
228
    }
229
230
    /**
231
     * Get the default HTTP Client
232
     *
233
     * @return HTTPClient
234
     */
235 38
    public function getDefaultHTTPClient()
236
    {
237 38
        return new HTTPClient(array('base_url' => rtrim($this->baseEndpoint, '/') . '/'));
238
    }
239
240 28
    public function performRequest($method, $path, array $params = [])
241
    {
242 28
        $request = $this->buildRequest($method, $path, $params);
243
244
        try {
245 28
            $response = $this->httpClient->send($request);
246 28
            $content = json_decode($response->getBody()->getContents(), true);
247 28
            return $this->createResponseFromData($content);
248
        } catch (ClientException $ex) {
249
            if ($ex->getResponse()->getStatusCode() == 401) {
250
                $message = sprintf('Unauthorized %s Request to %s', $request->getMethod(), $request->getUrl());
251
                throw new UnauthorizedRequestException($message);
252
            }
253
254
            throw $ex;
255
        }
256
    }
257
258
    /**
259
     * Build a request object
260
     *
261
     * @param $method
262
     * @param $path
263
     * @param $params
264
     *
265
     * @return \GuzzleHttp\Message\Request
266
     */
267 30
    public function buildRequest($method, $path, array $params = [])
268
    {
269 30
        $body = ArrayUtils::get($params, 'body', []);
270 30
        $query = ArrayUtils::get($params, 'query', []);
271
272
        $options = [
273 30
            'auth' => [$this->accessToken, '']
274 30
        ];
275
276 30
        if (in_array($method, ['POST', 'PUT']) && $body) {
277
            $options['body'] = $body;
278
        }
279
280 30
        $request = $this->httpClient->createRequest($method, $path, $options);
281
282 30
        if ($query) {
283
            $q = $request->getQuery();
284
            foreach($query as $key => $value) {
285
                $q->set($key, $value);
286
            }
287
        }
288
289 30
        return $request;
290
    }
291
292
    /**
293
     * Build a endpoint path based on a format
294
     *
295
     * @param string $pathFormat
296
     * @param array $variables
297
     *
298
     * @return string
299
     */
300 24
    public function buildPath($pathFormat, $variables = [])
301
    {
302 24
        return vsprintf(ltrim($pathFormat, '/'), $variables);
303
    }
304
}
305