Completed
Push — d64 ( 47f128...a6abe6 )
by Welling
02:17
created

BaseClientRemote::getBaseEndpoint()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

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