Completed
Push — d64 ( 885ace...e16005 )
by Welling
02:19
created

BaseClientRemote   A

Complexity

Total Complexity 23

Size/Duplication

Total Lines 277
Duplicated Lines 0 %

Coupling/Cohesion

Components 2
Dependencies 8

Test Coverage

Coverage 81.54%

Importance

Changes 0
Metric Value
dl 0
loc 277
ccs 53
cts 65
cp 0.8154
rs 10
c 0
b 0
f 0
wmc 23
lcom 2
cbo 8

13 Methods

Rating   Name   Duplication   Size   Complexity  
B __construct() 0 21 5
A getBaseEndpoint() 0 4 1
A getBaseUrl() 0 4 1
A getAPIVersion() 0 4 1
A getAccessToken() 0 4 1
A setAccessToken() 0 4 1
A getInstanceKey() 0 4 1
A setHTTPClient() 0 4 1
A getHTTPClient() 0 4 1
A getDefaultHTTPClient() 0 4 1
A performRequest() 0 17 3
B buildRequest() 0 24 5
A buildPath() 0 4 1
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 TABLE_ENTRIES_ENDPOINT = 'tables/%s/rows';
89
    const TABLE_ENTRY_ENDPOINT = 'tables/%s/rows/%s';
90
    const TABLE_ENTRY_CREATE_ENDPOINT = 'tables/%s/rows';
91
    const TABLE_ENTRY_UPDATE_ENDPOINT = 'tables/%s/rows/%s';
92
    const TABLE_ENTRY_DELETE_ENDPOINT = 'tables/%s/rows/%s';
93
    const TABLE_LIST_ENDPOINT = 'tables';
94
    const TABLE_INFORMATION_ENDPOINT = 'tables/%s';
95
    const TABLE_PREFERENCES_ENDPOINT = 'tables/%s/preferences';
96
    const TABLE_BOOKMARKS_CREATE_ENDPOINT = 'bookmarks';
97
    const TABLE_CREATE_ENDPOINT = 'privileges/1'; // ID not being used but required @TODO: REMOVE IT
98
    const TABLE_DELETE_ENDPOINT = 'tables/%s';
99
100
    const COLUMN_LIST_ENDPOINT = 'tables/%s/columns';
101
    const COLUMN_CREATE_ENDPOINT = 'tables/%s/columns';
102
    const COLUMN_DELETE_ENDPOINT = 'tables/%s/columns/%s';
103
    const COLUMN_INFORMATION_ENDPOINT = 'tables/%s/columns/%s';
104
    const COLUMN_OPTIONS_CREATE_ENDPOINT = 'tables/%s/columns/%s/%s';
105
106
    const GROUP_LIST_ENDPOINT = 'groups';
107
    const GROUP_CREATE_ENDPOINT = 'groups';
108
    const GROUP_INFORMATION_ENDPOINT = 'groups/%s';
109
    const GROUP_PRIVILEGES_ENDPOINT = 'privileges/%s';
110
    const GROUP_PRIVILEGES_CREATE_ENDPOINT = 'privileges/%s';
111
112
    const FILE_LIST_ENDPOINT = 'files';
113
    const FILE_CREATE_ENDPOINT = 'files';
114
    const FILE_UPDATE_ENDPOINT = 'files/%s';
115
    const FILE_INFORMATION_ENDPOINT = 'files/%s';
116
117
    const SETTING_LIST_ENDPOINT = 'settings';
118
    const SETTING_COLLECTION_ENDPOINT = 'settings/%s';
119
120
    const MESSAGES_CREATE_ENDPOINT = 'messages/rows';
121
    const MESSAGES_USER_ENDPOINT = 'messages/rows/%s';
122
123 38
    public function __construct($accessToken, $options = [])
124
    {
125 38
        $this->accessToken = $accessToken;
126
127 38
        if (isset($options['base_url'])) {
128 4
            $this->baseUrl = rtrim($options['base_url'], '/');
129 4
            $this->baseEndpoint = $this->baseUrl . '/api';
130 4
        }
131
132 38
        $instanceKey = isset($options['instance_key']) ? $options['instance_key'] : false;
133 38
        if ($instanceKey) {
134 2
            $this->instanceKey = $instanceKey;
135 2
            $this->baseUrl = sprintf($this->hostedBaseUrlFormat, $instanceKey);
136 2
            $this->baseEndpoint = $this->baseUrl . '/api';
137 2
        }
138
139 38
        $this->apiVersion = isset($options['version']) ? $options['version'] : 1;
140 38
        $this->baseEndpoint .= '/' . $this->getAPIVersion();
141
142 38
        $this->setHTTPClient($this->getDefaultHTTPClient());
143 38
    }
144
145
    /**
146
     * Get the base endpoint url
147
     *
148
     * @return string
149
     */
150 4
    public function getBaseEndpoint()
151
    {
152 4
        return $this->baseEndpoint;
153
    }
154
155
    /**
156
     * Get the base url
157
     *
158
     * @return string
159
     */
160 2
    public function getBaseUrl()
161 2
    {
162 2
        return $this->baseUrl;
163
    }
164
165
    /**
166
     * Get API Version
167
     *
168
     * @return int|string
169
     */
170 38
    public function getAPIVersion()
171
    {
172 38
        return $this->apiVersion;
173
    }
174
175
    /**
176
     * Get the authentication access token
177
     *
178
     * @return string
179
     */
180 2
    public function getAccessToken()
181
    {
182 2
        return $this->accessToken;
183
    }
184
185
    /**
186
     * Set a new authentication access token
187
     *
188
     * @param $newAccessToken
189
     */
190 2
    public function setAccessToken($newAccessToken)
191
    {
192 2
        $this->accessToken = $newAccessToken;
193 2
    }
194
195
    /**
196
     * Get the Directus hosted instance key
197
     *
198
     * @return null|string
199
     */
200 4
    public function getInstanceKey()
201
    {
202 4
        return $this->instanceKey;
203
    }
204
205
    /**
206
     * Set the HTTP Client
207
     *
208
     * @param HTTPClient $httpClient
209
     */
210 38
    public function setHTTPClient(HTTPClient $httpClient)
211
    {
212 38
        $this->httpClient = $httpClient;
213 38
    }
214
215
    /**
216
     * Get the HTTP Client
217
     *
218
     * @return HTTPClient|null
219
     */
220 38
    public function getHTTPClient()
221
    {
222 38
        return $this->httpClient;
223
    }
224
225
    /**
226
     * Get the default HTTP Client
227
     *
228
     * @return HTTPClient
229
     */
230 38
    public function getDefaultHTTPClient()
231
    {
232 38
        return new HTTPClient(array('base_url' => rtrim($this->baseEndpoint, '/') . '/'));
233
    }
234
235 28
    public function performRequest($method, $path, array $params = [])
236
    {
237 28
        $request = $this->buildRequest($method, $path, $params);
238
239
        try {
240 28
            $response = $this->httpClient->send($request);
241 28
            $content = json_decode($response->getBody()->getContents(), true);
242 28
            return $this->createResponseFromData($content);
243
        } catch (ClientException $ex) {
244
            if ($ex->getResponse()->getStatusCode() == 401) {
245
                $message = sprintf('Unauthorized %s Request to %s', $request->getMethod(), $request->getUrl());
246
                throw new UnauthorizedRequestException($message);
247
            }
248
249
            throw $ex;
250
        }
251
    }
252
253
    /**
254
     * Build a request object
255
     *
256
     * @param $method
257
     * @param $path
258
     * @param $params
259
     *
260
     * @return \GuzzleHttp\Message\Request
261
     */
262 30
    public function buildRequest($method, $path, array $params = [])
263
    {
264 30
        $body = ArrayUtils::get($params, 'body', []);
265 30
        $query = ArrayUtils::get($params, 'query', []);
266
267
        $options = [
268 30
            'auth' => [$this->accessToken, '']
269 30
        ];
270
271 30
        if (in_array($method, ['POST', 'PUT']) && $body) {
272
            $options['body'] = $body;
273
        }
274
275 30
        $request = $this->httpClient->createRequest($method, $path, $options);
276
277 30
        if ($query) {
278
            $q = $request->getQuery();
279
            foreach($query as $key => $value) {
280
                $q->set($key, $value);
281
            }
282
        }
283
284 30
        return $request;
285
    }
286
287
    /**
288
     * Build a endpoint path based on a format
289
     *
290
     * @param string $pathFormat
291
     * @param array $variables
292
     *
293
     * @return string
294
     */
295 24
    public function buildPath($pathFormat, $variables = [])
296
    {
297 24
        return vsprintf(ltrim($pathFormat, '/'), $variables);
298
    }
299
}
300