@@ -41,6 +41,28 @@ class Bridge
41
41
*/
42
42
protected $ client ;
43
43
44
+ /**
45
+ * The WatsonToken
46
+ *
47
+ * @var \FindBrok\WatsonBridge\Token
48
+ */
49
+ protected $ token ;
50
+
51
+ /**
52
+ * Decide which method to use when sending request
53
+ *
54
+ * @var string
55
+ */
56
+ protected $ authMethod = 'credentials ' ;
57
+
58
+ /**
59
+ * The limit for which we can re request token,
60
+ * when performing request
61
+ *
62
+ * @var int
63
+ */
64
+ protected $ exceptionThrottle = 0 ;
65
+
44
66
/**
45
67
* Default headers
46
68
*
@@ -58,14 +80,18 @@ class Bridge
58
80
* @param string $password
59
81
* @param string $endpoint
60
82
*/
61
- public function __construct ($ username = null , $ password = null , $ endpoint = null )
83
+ public function __construct ($ username , $ password , $ endpoint )
62
84
{
63
85
//Set Username, Password and Endpoint
64
86
$ this ->username = $ username ;
65
87
$ this ->password = $ password ;
66
88
$ this ->endpoint = $ endpoint ;
89
+
67
90
//Set HttpClient
68
- $ this ->setClient ();
91
+ $ this ->setClient ($ endpoint );
92
+
93
+ //Set Token
94
+ $ this ->token = new Token ($ this ->username );
69
95
}
70
96
71
97
/**
@@ -107,16 +133,73 @@ public function getHeaders()
107
133
return $ this ->headers ;
108
134
}
109
135
136
+ /**
137
+ * Fetch token from Watson and Save it locally
138
+ *
139
+ * @param bool $incrementThrottle
140
+ * @return void
141
+ */
142
+ public function fetchToken ($ incrementThrottle = false )
143
+ {
144
+ //Increment throttle if needed
145
+ if ($ incrementThrottle ) {
146
+ $ this ->incrementThrottle ();
147
+ }
148
+ //Reset Client
149
+ $ this ->setClient ($ this ->getAuthorizationEndpoint ());
150
+ //Get the token response
151
+ $ response = $ this ->get ('v1/token ' , [
152
+ 'url ' => $ this ->endpoint
153
+ ]);
154
+ //Extract
155
+ $ token = json_decode ($ response ->getBody ()->getContents (), true );
156
+ //Reset client
157
+ $ this ->setClient ($ this ->endpoint );
158
+ //Update token
159
+ $ this ->token ->updateToken ($ token ['token ' ]);
160
+ }
161
+
162
+ /**
163
+ * Get a token for authorization from Watson or Storage
164
+ *
165
+ * @return string
166
+ */
167
+ public function getToken ()
168
+ {
169
+ //Token is not valid
170
+ if (! $ this ->token ->isValid ()) {
171
+ //Fetch from Watson
172
+ $ this ->fetchToken ();
173
+ }
174
+
175
+ //Return token
176
+ return $ this ->token ->getToken ();
177
+ }
178
+
179
+ /**
180
+ * Get the authorization endpoint for getting tokens
181
+ *
182
+ * @return string
183
+ */
184
+ public function getAuthorizationEndpoint ()
185
+ {
186
+ //Parse the endpoint
187
+ $ parsedEndpoint = collect (parse_url ($ this ->endpoint ));
188
+ //Return auth url
189
+ return $ parsedEndpoint ->get ('scheme ' ).':// ' .$ parsedEndpoint ->get ('host ' ).'/authorization/api/ ' ;
190
+ }
191
+
110
192
/**
111
193
* Creates the http client
112
194
*
195
+ * @param string $endpoint
113
196
* @return void
114
197
*/
115
- private function setClient ()
198
+ public function setClient ($ endpoint = null )
116
199
{
117
200
//Create client using API endpoint
118
201
$ this ->client = new Client ([
119
- 'base_uri ' => $ this ->endpoint ,
202
+ 'base_uri ' => ! is_null ( $ endpoint ) ? $ endpoint : $ this ->endpoint ,
120
203
]);
121
204
}
122
205
@@ -164,7 +247,7 @@ public function failedRequest($response)
164
247
}
165
248
166
249
/**
167
- * Make a Request to Watson
250
+ * Make a Request to Watson with credentials Auth
168
251
*
169
252
* @param string $method
170
253
* @param string $uri
@@ -175,8 +258,17 @@ public function request($method = 'GET', $uri = '', $options = [])
175
258
{
176
259
try {
177
260
//Make the request
178
- return $ this ->getClient ()->request ($ method , $ uri , $ options );
261
+ return $ this ->getClient ()->request ($ method , $ uri , $ this -> getRequestOptions ( $ options) );
179
262
} catch (ClientException $ e ) {
263
+ //We are using token auth and probably token expired
264
+ if ($ this ->authMethod == 'token ' && $ e ->getCode () == 401 && ! $ this ->isThrottledReached ()) {
265
+ //Try refresh token
266
+ $ this ->fetchToken (true );
267
+ //Try requesting again
268
+ return $ this ->request ($ method , $ uri , $ options );
269
+ }
270
+ //Clear throttle for this request
271
+ $ this ->clearThrottle ();
180
272
//Call Failed Request
181
273
$ this ->failedRequest ($ e ->getResponse ());
182
274
}
@@ -193,12 +285,8 @@ public function request($method = 'GET', $uri = '', $options = [])
193
285
*/
194
286
private function send ($ method = 'POST ' , $ uri , $ data , $ type = 'json ' )
195
287
{
196
- //Make a Post Request
197
- $ response = $ this ->request ($ method , $ uri , $ this ->cleanOptions ([
198
- 'headers ' => $ this ->getHeaders (),
199
- 'auth ' => $ this ->getAuth (),
200
- $ type => $ data
201
- ]));
288
+ //Make the Request to Watson
289
+ $ response = $ this ->request ($ method , $ uri , [$ type => $ data ]);
202
290
//Request Failed
203
291
if ($ response ->getStatusCode () != 200 ) {
204
292
//Throw Watson Bridge Exception
@@ -208,6 +296,78 @@ private function send($method = 'POST', $uri, $data, $type = 'json')
208
296
return $ response ;
209
297
}
210
298
299
+ /**
300
+ * Get Request options to pass along
301
+ *
302
+ * @param array $initial
303
+ * @return array
304
+ */
305
+ public function getRequestOptions ($ initial = [])
306
+ {
307
+ //Define options
308
+ $ options = collect ($ initial );
309
+ //Define an auth option
310
+ if ($ this ->authMethod == 'credentials ' ) {
311
+ $ options = $ options ->merge ([
312
+ 'auth ' => $ this ->getAuth (),
313
+ ]);
314
+ } elseif ($ this ->authMethod == 'token ' ) {
315
+ $ this ->appendHeaders ([
316
+ 'X-Watson-Authorization-Token ' => $ this ->getToken ()
317
+ ]);
318
+ }
319
+ //Put Headers in options
320
+ $ options = $ options ->merge ([
321
+ 'headers ' => $ this ->getHeaders (),
322
+ ]);
323
+ //Clean and return
324
+ return $ this ->cleanOptions ($ options ->all ());
325
+ }
326
+
327
+ /**
328
+ * Change the auth method
329
+ *
330
+ * @param string $method
331
+ * @return self
332
+ */
333
+ public function useAuthMethodAs ($ method = 'credentials ' )
334
+ {
335
+ //Change auth method
336
+ $ this ->authMethod = $ method ;
337
+ //Return object
338
+ return $ this ;
339
+ }
340
+
341
+ /**
342
+ * Checks if throttle is reached
343
+ *
344
+ * @return bool
345
+ */
346
+ public function isThrottledReached ()
347
+ {
348
+ return $ this ->exceptionThrottle >= 2 ;
349
+ }
350
+
351
+ /**
352
+ * Increment throttle
353
+ *
354
+ * @return void
355
+ */
356
+ public function incrementThrottle ()
357
+ {
358
+ $ this ->exceptionThrottle ++;
359
+ }
360
+
361
+ /**
362
+ * Clears throttle counter
363
+ *
364
+ * @return void
365
+ */
366
+ public function clearThrottle ()
367
+ {
368
+ $ this ->exceptionThrottle = 0 ;
369
+ }
370
+
211
371
/**
212
372
* Make a GET Request to Watson
213
373
*
0 commit comments