forked from Nchalenko/okta-sdk-php
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathDefaultDataStore.php
More file actions
454 lines (384 loc) · 14.2 KB
/
Copy pathDefaultDataStore.php
File metadata and controls
454 lines (384 loc) · 14.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
<?php
/******************************************************************************
* Copyright 2017 Okta, Inc. *
* *
* Licensed under the Apache License, Version 2.0 (the "License"); *
* you may not use this file except in compliance with the License. *
* You may obtain a copy of the License at *
* *
* http://www.apache.org/licenses/LICENSE-2.0 *
* *
* Unless required by applicable law or agreed to in writing, software *
* distributed under the License is distributed on an "AS IS" BASIS, *
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. *
* See the License for the specific language governing permissions and *
* limitations under the License. *
******************************************************************************/
namespace Okta\DataStore;
use Cache\Adapter\Common\CacheItem;
use GuzzleHttp\Psr7\Query;
use Http\Client\Common\Plugin\AuthenticationPlugin;
use Http\Client\Common\PluginClient;
use Http\Client\HttpClient;
use Http\Discovery\HttpClientDiscovery;
use Http\Discovery\MessageFactoryDiscovery;
use Http\Discovery\UriFactoryDiscovery;
use Http\Message\MessageFactory;
use Http\Message\UriFactory;
use Okta\Client;
use Okta\Exceptions\Error;
use Okta\Exceptions\ResourceException;
use Okta\Resource\AbstractCollection;
use Okta\Resource\AbstractResource;
use Okta\Utilities\AuthorizationMode;
use Okta\Utilities\SswsAuth;
use Okta\Utilities\UserAgentBuilder;
use Psr\Http\Message\UriInterface;
class DefaultDataStore
{
/**
* @var \Http\Message\UriFactory $uriFactory Uri Factory.
*/
protected $uriFactory;
/**
* @var \Http\Message\MessageFactory $messageFactory Message Factory.
*/
protected $messageFactory;
/**
* @var string $token The token for your organization.
*/
private $token;
/**
* @var string $organizationUrl The organization Url.
*/
private $organizationUrl;
/**
* @var PluginClient $httpClient The Http Client Instance.
*/
private $httpClient;
/**
* @var string $baseUrl The base url for calls. Generated from Organization
* URL/api/v1
*/
private $baseUrl;
/**
* @var \Okta\Cache\CacheManager The CacheManager Instance from the Client.
*/
private $cacheManager;
/**
* @var AbstractResource A place to temporally store the resource we are working with.
*/
private $resource;
/**
* DefaultDataStore constructor.
*
* @param string $token
* @param string $organizationUrl
* @param HttpClient|NULL $httpClient
* @param AuthorizationMode|NULL $authorizationMode
*/
public function __construct(string $token, string $organizationUrl, HttpClient $httpClient = null, AuthorizationMode $authorizationMode = null)
{
$this->token = $token;
$this->organizationUrl = $organizationUrl;
if($authorizationMode === null) {
$authorizationMode = new AuthorizationMode(AuthorizationMode::SSWS);
}
$authenticationPlugin = new AuthenticationPlugin(
$authorizationMode->getDriver()
);
$this->httpClient = new PluginClient(
$httpClient ?: HttpClientDiscovery::find(),
[ $authenticationPlugin ]
);
$this->uriFactory = UriFactoryDiscovery::find();
$this->messageFactory = MessageFactoryDiscovery::find();
$this->baseUrl = $this->organizationUrl . '/api/v1';
}
/**
* Create a new instance of a class with the provided properties.
*
* @param string $class Class to instantiate.
* @param \stdClass|NULL $properties The properties you want to use to instantiate.
* @param array $options Any options you want to set.
* @return object
*/
public function instantiate(string $class, \stdClass $properties = null, array $options = [])
{
$propertiesArr = array($properties, $options);
$class = new \ReflectionClass($class);
array_unshift($propertiesArr, Client::getInstance()->getDataStore());
$newClass = $class->newInstanceArgs($propertiesArr);
return $newClass;
}
/**
* Get a resource from the API.
*
* @param string $href The unique identifier for the href.
* @param string $className The class name to return as.
* @param string $path The path to the resource.
* @param array $options The options to use when making the request.
* @return AbstractResource
*/
public function getResource($href, $className, $path, array $options = []): AbstractResource
{
$uri = $this->uriFactory->createUri($this->organizationUrl . '/api/v1' . $path . '/' . $href);
if (key_exists('query', $options)) {
$queryString = $this->getQueryString($options['query']);
$uri = $uri->withQuery($this->appendQueryValues($uri->getQuery(), $queryString));
}
$result = $this->executeRequest('GET', $uri);
return new $className(null, $result);
}
/**
* Get a collection of items.
*
* @param string $href The unique identifier for the href.
* @param string $className The class name for each item in the collection.
* @param string $collection the collection type to return as.
* @param array $options Options to add to the request.
* @return AbstractCollection
*/
public function getCollection($href, $className, $collection, array $options = []): AbstractCollection
{
$uri = $this->uriFactory->createUri($this->organizationUrl . $href);
if (key_exists('query', $options)) {
$queryString = $this->getQueryString($options['query']);
$uri = $uri->withQuery($this->appendQueryValues($uri->getQuery(), $queryString));
}
$toCollect = [];
$result = $this->executeRequest('GET', $uri);
foreach ($result as $item) {
$toCollect[] = new $className(null, $item);
}
return new $collection($toCollect);
}
/**
* Issues a save request to the API.
*
* @param string $href The path to the resource
* @param AbstractResource $resource The resource to save.
* @param string $returnType The Resource class you want to return.
*
* @return mixed
*/
public function saveResource($href, $resource, $returnType)
{
$this->resource = $resource;
$uri = $this->uriFactory->createUri($this->organizationUrl . '/api/v1' . $href . '/' . $resource->getId());
$result = $this->executeRequest('POST', $uri, json_encode($this->toStdClass($resource)));
$resource = new $returnType(null, $result);
return $resource;
}
/**
* Issues a save request to the API.
*
* @param string $href The path to the resource
* @param AbstractResource $resource The resource to save.
* @param string $returnType The Resource class you want to return.
* @param array $query The query of the URL
*
* @return mixed
*/
public function createResource($href, $resource, $returnType, $query=[])
{
$this->resource = $resource;
$uri = $this->uriFactory->createUri($this->organizationUrl . '/api/v1' . $href);
if(!empty($query)) {
$uri = $uri->withQuery(http_build_query($query));
}
$result = $this->executeRequest('POST', $uri, json_encode($this->toStdClass($resource)));
return new $returnType(null, $result);
}
/**
* Issues a delete request to the API.
*
* @param string $href The path to the resource
* @param AbstractResource $resource The resource to save.
*
* @return mixed
*/
public function deleteResource($href, $resource)
{
$this->resource = $resource;
$uri = $this->uriFactory->createUri($this->organizationUrl . '/api/v1' . $href . '/' . $resource->getId());
$result = $this->executeRequest('DELETE', $uri);
return $result;
}
/**
* Make the request.
*
* @param string $method The type of request.
* @param UriInterface $uri The URI object of the request.
* @param string $body The body of the request.
* @param array $options The options for the request.
*
* @return mixed|null
* @throws ResourceException
*/
public function executeRequest($method, UriInterface $uri, $body = '', array $options = [])
{
$cacheManager = $cacheManager = Client::getInstance()->getCacheManager();
$cacheKey = $cacheManager->createCacheKey($uri);
if('GET' == $method && $cacheManager->pool()->hasItem($cacheKey)) {
return $cacheManager->pool()->getItem($cacheKey)->get();
}
$headers = [];
$headers['Accept'] = 'application/json';
$userAgentBuilder = new UserAgentBuilder;
$headers['User-Agent'] = $userAgentBuilder->setOsName(php_uname('s'))
->setOsVersion(php_uname('r'))
->setPhpVersion(phpversion())
->build();
if ($body) {
$headers['Content-Type'] = 'application/json';
$headers['Content-Length'] = strlen($body);
}
if (key_exists('query', $options)) {
$queryString = $this->getQueryString($options['query']);
$uri = $uri->withQuery($this->appendQueryValues($uri->getQuery(), $queryString));
}
$request = $this->messageFactory->createRequest($method, $uri, $headers, $body);
$response = $this->httpClient->sendRequest($request);
$result = $response->getBody() ? json_decode($response->getBody()) : null;
if (isset($result) && $result instanceof \stdClass) {
$result->httpStatus = $response->getStatusCode();
}
if ($response->getStatusCode() < 200 || $response->getStatusCode() > 299) {
$error = new Error($result);
throw new ResourceException($error);
}
if (!is_array($result)) {
switch($method) {
case 'GET':
if(null !== $result) {
$cacheManager->save($uri, $result);
}
break;
case 'POST':
case 'PUT':
if(null !== $result) {
$cacheManager->delete($uri, $result);
$cacheManager->save($uri, $result);
}
break;
case 'DELETE':
if(null !== $this->resource) {
$cacheManager->delete($uri, $this->toStdClass($this->resource));
}
break;
}
}
return $result;
}
/**
* Convert an AbstractResource object to a stdClass object.
*
* @param AbstractResource $resource The resource to convert.
* @return \stdClass
*/
private function toStdClass(AbstractResource $resource)
{
$propertyNames = $resource->getPropertyNames(true);
$properties = new \stdClass();
foreach ($propertyNames as $name) {
$property = $resource->getProperty($name);
$properties->$name = $property;
}
return $properties;
}
/**
* Get the query string from the options.
*
* @param array $options The options to get the query string from.
* @return array
*/
private function getQueryString(array $options)
{
$query = array();
foreach ($options as $key => $opt) {
$query[$key] = !is_bool($opt)?
strval($opt) :
var_export($opt, true);
}
return $query;
}
/**
* Adapted from Guzzle PSR-7, by Michael Dowling et al.
* Licensed under the MIT license
*
* Any existing query string values that exactly match the provided key are
* removed and replaced with the key value pair in the dictionary.
*
* A value of null will set the query string key without a value, e.g. "key"
* instead of "key=value".
*
* @param string $currentQuery The current query string
* @param array $queryDictionary A key-value array of query parameters to append to the query string
*
* @return string
*/
private function appendQueryValues($currentQuery, $queryDictionary)
{
$currentQueryParts = Query::parse($currentQuery);
if ($currentQuery == '') {
$result = [];
}
foreach ($queryDictionary as $key => $value) {
$key = strtr($key, ['=' => '%3D', '&' => '%26']);
if ($value !== null) {
$result[$key] = strtr($value, ['=' => '%3D', '&' => '%26']);
} else {
$result[$key] = $key;
}
}
$result = array_replace_recursive($currentQueryParts, $result);
return Query::build($result);
}
/**
* Get the current PluginClient instance.
*
* @return PluginClient
*/
public function getHttpClient(): PluginClient
{
return $this->httpClient;
}
/**
* Get the current MessageFactory instance.
*
* @return MessageFactory
*/
public function getMessageFactory(): MessageFactory
{
return $this->messageFactory;
}
/**
* Get the current UriFactory instance.
*
* @return UriFactory
*/
public function getUriFactory(): UriFactory
{
return $this->uriFactory;
}
/**
* Get the organization url.
*
* @return string
*/
public function getOrganizationUrl(): string
{
return $this->organizationUrl;
}
/**
* Create an instance of Uri that can be used in the request.
*
* @param string $uri The URI to convert into a usable uri object.
* @return UriInterface
*/
public function buildUri(string $uri): UriInterface
{
return $this->uriFactory->createUri($uri);
}
}