forked from Brunojoe1994/-data
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathQueryManager.php
More file actions
625 lines (565 loc) · 19.9 KB
/
QueryManager.php
File metadata and controls
625 lines (565 loc) · 19.9 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
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
<?php
declare(strict_types=1);
namespace Strata\Data\Query;
use Strata\Data\Collection;
use Strata\Data\CollectionInterface;
use Strata\Data\DataProviderInterface;
use Strata\Data\Exception\CacheException;
use Strata\Data\Exception\MissingDataProviderException;
use Strata\Data\Exception\QueryManagerException;
use Strata\Data\Http\Http;
use Strata\Data\Http\Response\CacheableResponse;
use Symfony\Contracts\Cache\CacheInterface;
use Symfony\Contracts\HttpClient\HttpClientInterface;
/**
* Class to help manage running queries against data providers
*/
class QueryManager
{
const DATA_PROVIDER_NAME = 'name';
const DATA_PROVIDER_OBJECT = 'object';
const DATA_PROVIDER_CLASS = 'class';
const DATA_PROVIDER_QUERIES = 'queries';
/** @var QueryInterface[] */
private array $queries = [];
private array $dataProviders = [];
private ?HttpClientInterface $httpClient = null;
private bool $cacheEnabled = false;
private ?CacheInterface $cache = null;
private ?int $cacheLifetime = null;
private array $cacheTags = [];
/**
* Set a shared HTTP client to be used across all HTTP data providers
*
* This is useful to run concurrent requests
*
* @param HttpClientInterface $httpClient
*/
public function setHttpClient(HttpClientInterface $httpClient)
{
$this->httpClient = $httpClient;
foreach ($this->getDataProviders() as $dataProvider) {
if ($dataProvider instanceof Http) {
$dataProvider->setHttpClient($httpClient);
}
}
}
/**
* Share the same HTTP client across all HTTP compatible data providers
*
* This gets the HTTP client from the first data provider and sets this across all HTTP data providers
* Any future data providers you add will also have the same HTTP client set
* This is useful to run concurrent requests
*
* @throws MissingDataProviderException
*/
public function shareHttpClient()
{
$httpDataProvider = null;
foreach ($this->getDataProviders() as $dataProvider) {
if ($dataProvider instanceof Http) {
$httpDataProvider = $dataProvider;
break;
}
}
if (!($httpDataProvider instanceof Http)) {
throw new MissingDataProviderException('You must setup at least one HTTP data provider before sharing HTTP client across all HTTP data providers');
}
$this->setHttpClient($httpDataProvider->getHttpClient());
}
/**
* Add a data provider to use with queries
* @param string $name
* @param DataProviderInterface $dataProvider
*/
public function addDataProvider(string $name, DataProviderInterface $dataProvider)
{
if ($this->hasCache()) {
// Set cache
$dataProvider->setCache($this->cache, $this->cacheLifetime);
if ($this->isCacheEnabled()) {
$dataProvider->enableCache();
} else {
$dataProvider->disableCache();
}
}
if (!empty($this->cacheTags)) {
// If cache tags exist and cache adapter is compatible, set them
if ($dataProvider->getCache()->isTaggable()) {
$dataProvider->setCacheTags($this->cacheTags);
}
}
if ($dataProvider instanceof Http) {
// Set shared HTTP client
if (!is_null($this->httpClient) && !$dataProvider->hasHttpClient()) {
$dataProvider->setHttpClient($this->httpClient);
}
}
$this->dataProviders[$name] = [
self::DATA_PROVIDER_NAME => $name,
self::DATA_PROVIDER_CLASS => get_class($dataProvider),
self::DATA_PROVIDER_OBJECT => $dataProvider,
self::DATA_PROVIDER_QUERIES => [],
];
}
/**
* Does the named data provider exist?
*
* @param string $name
* @return bool
*/
public function hasDataProvider(string $name): bool
{
return (isset($this->dataProviders[$name]));
}
/**
* Return all data provider objects
*
* @return DataProviderInterface[]
*/
public function getDataProviders(): array
{
$dataProviders = [];
foreach ($this->dataProviders as $item) {
$dataProviders[] = $item[self::DATA_PROVIDER_OBJECT];
}
return $dataProviders;
}
/**
* Return data provider by name
*
* @param string $name Data provider name
* @return DataProviderInterface
* @throws MissingDataProviderException
*/
public function getDataProvider(string $name): DataProviderInterface
{
if (!$this->hasDataProvider($name)) {
throw new MissingDataProviderException(sprintf('Cannot find data provider %s', $name));
}
return $this->dataProviders[$name][self::DATA_PROVIDER_OBJECT];
}
/**
* Return queries for a named data provider
*
* @param string $name
* @return QueryInterface[]
* @throws MissingDataProviderException
*/
public function getDataProviderQueries(string $name): array
{
if (!$this->hasDataProvider($name)) {
throw new MissingDataProviderException(sprintf('Cannot find data provider %s', $name));
}
return $this->dataProviders[$name][self::DATA_PROVIDER_QUERIES];
}
/**
* Return classname for the named data provider object
*
* @param string $name
* @return string
* @throws MissingDataProviderException
*/
public function getDataProviderClass(string $name): string
{
if (!$this->hasDataProvider($name)) {
throw new MissingDataProviderException(sprintf('Cannot find data provider %s', $name));
}
return $this->dataProviders[$name][self::DATA_PROVIDER_CLASS];
}
/**
* Return first compatible data provider name we can find for passed query
* @param QueryInterface $query
* @return string Data provider name
* @throws MissingDataProviderException
*/
public function getDataProviderNameForQuery(QueryInterface $query): string
{
$requiredClass = $query->getRequiredDataProviderClass();
foreach ($this->dataProviders as $item) {
$class = $item[self::DATA_PROVIDER_CLASS];
if ($class === $requiredClass) {
return $item[self::DATA_PROVIDER_NAME];
}
}
throw new MissingDataProviderException(sprintf('Cannot find a compatible data provider (%s) for query', $requiredClass));
}
/**
* Add a query (does not run the query, this happens on data access)
*
* @param string $queryName
* @param QueryInterface $query Query
* @param string|null $dataProviderName Data provider to use with query, if not set use last added data provider
* @throws QueryManagerException
*/
public function add(string $queryName, QueryInterface $query, ?string $dataProviderName = null)
{
if ($this->hasQuery($queryName)) {
throw new QueryManagerException(sprintf('Query name %s already exists in the Query Manager, please give this query a unique name', $queryName));
}
if (!$query->hasDataProvider()) {
if ($dataProviderName === null) {
// Get compatible data provider if not set in method argument
$dataProviderName = $this->getDataProviderNameForQuery($query);
}
$dataProvider = $this->getDataProvider($dataProviderName);
$query->setDataProvider($dataProvider);
}
// Prepare request
$query->prepare();
// Add query to query stack
$this->queries[$queryName] = $query;
// Add query to data providers array
$this->dataProviders[$dataProviderName][self::DATA_PROVIDER_QUERIES][$queryName] = $query;
}
/**
* Add multiple queries to the data manager
* @param array $queries Array of name => query objects
*/
public function addQueries(array $queries)
{
foreach ($queries as $name => $query) {
if (is_string($name) && !empty($name) && $query instanceof QueryInterface) {
$this->add($name, $query);
}
}
}
/**
* Run queries on data access
*
* Only runs a query once, you can force a query to be re-run via $query->clearResponse()
*
* This should run multiple queries concurrently
*/
protected function runConcurrentQueries()
{
foreach ($this->queries as $query) {
// Skip if already run, you can still manually re-run a query via $query->run()
if ($query->hasResponseRun()) {
continue;
}
// Skip queries marked as do not run concurrently
if (!$query->isConcurrent()) {
continue;
}
// Run a query
$query->run();
}
}
/**
* Run a query
*
* This method either run all queries concurrently, or just this single query is the query is set as non-concurrent
*
* @param QueryInterface $query
*/
protected function runQuery(QueryInterface $query)
{
if (!$query->hasResponseRun()) {
if ($query->isConcurrent()) {
$this->runConcurrentQueries();
} else {
$query->run();
}
}
}
/**
* Does a named query exist?
* @param string $name
* @return bool
*/
public function hasQuery(string $name): bool
{
return array_key_exists($name, $this->queries);
}
/**
* Return a query by name
* @param string $name
* @return QueryInterface|null
*/
public function getQuery(string $name): ?QueryInterface
{
if ($this->hasQuery($name)) {
return $this->queries[$name];
}
return null;
}
/**
* Return all queries in the query manager
* @return QueryInterface[]
*/
public function getQueries(): array
{
return $this->queries;
}
/**
* Get response by query name
* @param string $queryName
* @return CacheableResponse
* @throws QueryManagerException
*/
public function getResponse(string $queryName): CacheableResponse
{
if (!$this->hasQuery($queryName)) {
throw new QueryManagerException(sprintf('Cannot find query with query name "%s"', $queryName));
}
// Either run all queries concurrently, or just this single query
$query = $this->getQuery($queryName);
$this->runQuery($query);
if (!$query->hasResponseRun()) {
throw new QueryManagerException(sprintf('Response has not run for query name "%s"', $queryName));
}
return $query->getResponse();
}
/**
* Clear response from a query (allows you to re-run queries)
*
* @param string $queryName
* @throws QueryManagerException
*/
public function clearResponse(string $queryName)
{
if (!$this->hasQuery($queryName)) {
throw new QueryManagerException(sprintf('Cannot find query with query name "%s"', $queryName));
}
$query = $this->getQuery($queryName);
$query->clearResponse();
}
/**
* Whether a query response has been returned from the cache
*
* @param string $queryName
* @return bool|null True if query response returned from cache, null if query response has not yet run
* @throws QueryManagerException
*/
public function isHit(string $queryName): ?bool
{
if (!$this->hasQuery($queryName)) {
throw new QueryManagerException(sprintf('Cannot find query with query name "%s"', $queryName));
}
$query = $this->getQuery($queryName);
if (!$query->hasResponseRun()) {
return null;
}
return $query->getResponse()->isHit();
}
/**
* Return a data item
*
* Default functionality is to return decoded data as an array
*
* @param string $queryName
* @param string|null $rootPropertyPath Property path to root element to select data from, null if no data returned
* @return mixed
* @throws QueryManagerException
*/
public function get(string $queryName, ?string $rootPropertyPath = null)
{
if (!$this->hasQuery($queryName)) {
throw new QueryManagerException(sprintf('Cannot find query with query name "%s"', $queryName));
}
// Either run all queries concurrently, or just this single query
$query = $this->getQuery($queryName);
$this->runQuery($query);
if (!$query->hasResponseRun()) {
throw new QueryManagerException(sprintf('Response has not run for query name "%s"', $queryName));
}
// Set root property path, then reset it
if ($rootPropertyPath !== null) {
$originalPath = $query->getRootPropertyPath();
$query->setRootPropertyPath($rootPropertyPath);
}
$data = $query->get();
if ($rootPropertyPath !== null && is_string($originalPath)) {
$query->setRootPropertyPath($originalPath);
}
return $data;
}
/**
* Return a collection of data items with pagination
*
* Default functionality is to return decoded data as an array with pagination
*
* @return CollectionInterface
* @param string $queryName
* @param string|null $rootPropertyPath Property path to root element to select data from
* @throws QueryManagerException
*/
public function getCollection(string $queryName, ?string $rootPropertyPath = null): CollectionInterface
{
if (!$this->hasQuery($queryName)) {
throw new QueryManagerException(sprintf('Cannot find query with query name "%s"', $queryName));
}
// Either run all queries concurrently, or just this single query
$query = $this->getQuery($queryName);
$this->runQuery($query);
if (!$query->hasResponseRun()) {
throw new QueryManagerException(sprintf('Response has not run for query name "%s"', $queryName));
}
// Set root property path, then reset it
if ($rootPropertyPath !== null) {
$originalPath = $query->getRootPropertyPath();
$query->setRootPropertyPath($rootPropertyPath);
}
$data = $query->getCollection();
if ($rootPropertyPath !== null && is_string($originalPath)) {
$query->setRootPropertyPath($originalPath);
}
return $data;
}
/**
* Set and enable the cache
*
* @param CacheInterface $cache
* @param int|null $defaultLifetime Default cache lifetime
*/
public function setCache(CacheInterface $cache, ?int $defaultLifetime = null)
{
$this->cache = $cache;
foreach ($this->getDataProviders() as $dataProvider) {
$dataProvider->setCache($this->cache, $defaultLifetime);
}
$this->enableCache();
}
/**
* Whether a cache object is set
* @return bool
*/
public function hasCache(): bool
{
return $this->cache instanceof CacheInterface;
}
/**
* Is the cache enabled?
*
* @return bool
*/
public function isCacheEnabled(): bool
{
return ($this->hasCache() && $this->cacheEnabled);
}
/**
* Enable cache for subsequent data requests
*
* @param ?int $lifetime
* @throws CacheException If cache not set
*/
public function enableCache(?int $lifetime = null)
{
$this->cacheEnabled = true;
$this->cacheLifetime = $lifetime;
foreach ($this->getDataProviders() as $dataProvider) {
$dataProvider->enableCache($lifetime);
}
}
/**
* Disable cache for subsequent data requests
*
*/
public function disableCache()
{
$this->cacheEnabled = false;
foreach ($this->getDataProviders() as $dataProvider) {
$dataProvider->disableCache();
}
}
/**
* Set cache tags to apply to all future saved cache items
*
* To remove tags do not pass any arguments and tags will be reset to an empty array
*
* @param array $tags
* @throws CacheException
* @throws QueryManagerException
*/
public function setCacheTags(array $tags = [])
{
$taggable = 0;
$this->cacheTags = $tags;
foreach ($this->getDataProviders() as $dataProvider) {
// If cache adapter is compatible, set them
if ($dataProvider->isCacheEnabled() && $dataProvider->getCache()->isTaggable()) {
$dataProvider->setCacheTags($tags);
$taggable++;
}
}
if ($taggable === 0) {
throw new QueryManagerException('No data providers contain a cache adapter that is compatible with tagging (must implement Symfony\Component\Cache\Adapter\TagAwareAdapter)');
}
}
/**
* Return cache tags currently set to the query manager
* @return array
*/
public function getCacheTags(): array
{
return $this->cacheTags;
}
/**
* Return debugging information for data collector (web profiler)
*
* @todo Query manager data collector - work in progress
* @return array
*/
public function getDataCollector(): array
{
$data = [
'dataProviders' => [],
'queries' => [],
'total' => 0,
'cached' => 0,
];
foreach ($this->dataProviders as $item) {
$dataProviderName = $item[self::DATA_PROVIDER_NAME];
/** @var DataProviderInterface $dataProvider */
$dataProvider = $item[self::DATA_PROVIDER_OBJECT];
$value = [
'name' => $dataProviderName,
'class' => get_class($dataProvider),
'baseUri' => $dataProvider->getBaseUri(),
'cacheEnabled' => $dataProvider->isCacheEnabled(),
];
$data['dataProviders'][] = $value;
/** @var QueryInterface $query */
foreach ($item[self::DATA_PROVIDER_QUERIES] as $queryName => $query) {
$value = [
'name' => $queryName,
'class' => get_class($query),
'type' => null,
'dataProvider' => $dataProviderName,
'hasResponse' => false
];
if ($query->hasResponseRun()) {
$data['total']++;
$value['hasResponse'] = true;
$value['cacheHit'] = $query->getResponse()->isHit();
$value['cacheAge'] = $query->getResponse()->getAge();
$value['baseUri'] = $dataProvider->getBaseUri();
$value['httpStatusCode'] = $query->getResponse()->getStatusCode();
$value['responseHeaders'] = $query->getResponse()->getHeaders();
$value['responseData'] = $query->getResponse()->getContent();
if ($query->getResponse()->isHit()) {
$data['cached']++;
}
}
if ($dataProvider instanceof Http) {
$value['dataProviderType'] = 'Http';
$options = $dataProvider->getCurrentDefaultOptions();
$value['httpHeaders'] = $options['headers'];
unset($options['headers']);
$value['httpOptions'] = $options;
}
if ($query instanceof Query) {
$value['type'] = 'Rest';
$value['uri'] = $query->getUri();
}
if ($query instanceof GraphQLQuery) {
$value['type'] = 'GraphQL';
$value['graphql'] = $query->getGraphQL();
}
$data['queries'][] = $value;
}
}
return $data;
}
}