Completed
Push — d64 ( df9164...be7046 )
by Welling
02:10
created

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